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); }}
package cn.chinatowercom.dataflow.datasource.controller;import cn.chinatowercom.dataflow.datasource.service.DataSetGroupService;import cn.chinatowercom.dataflow.datasource.service.VAuthModelService;import com.strongdata.dataflow.core.datasource.entity.DatasetGroup;import com.strongdata.dataflow.core.datasource.entity.dto.DataSetGroupDTO;import com.strongdata.dataflow.core.datasource.entity.dto.VAuthModelDTO;import com.strongdata.dataflow.core.datasource.entity.request.DataSetGroupRequest;import com.strongdata.dataflow.core.datasource.exception.DataManageException;import com.strongdata.dataflow.core.security.annotation.NoAuth;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import org.springframework.web.bind.annotation.*;import springfox.documentation.annotations.ApiIgnore;import javax.annotation.Resource;import java.util.Arrays;import java.util.List;/** * @Author gin * @Date 2023/2/18 8:29 下午 */@Api(tags = "数据集:数据集组")@RestController@RequestMapping("dataset/group")@NoAuth(value = false)public class DataSetGroupController { @Resource private DataSetGroupService dataSetGroupService; @Resource private VAuthModelService vAuthModelService; @ApiOperation("保存") @PostMapping("/save") public VAuthModelDTO save(@RequestBody DatasetGroup datasetGroup) throws DataManageException { DataSetGroupDTO result = dataSetGroupService.save(datasetGroup); return vAuthModelService.queryAuthModelByIds("dataset", Arrays.asList(result.getId())).get(0); } @ApiIgnore @PostMapping("/tree") public List<DataSetGroupDTO> tree(@RequestBody DataSetGroupRequest datasetGroup) { return dataSetGroupService.tree(datasetGroup); } @ApiOperation("删除") @PostMapping("/delete/{id}") public void delete(@PathVariable String id) throws DataManageException { dataSetGroupService.delete(id); } @ApiIgnore @PostMapping("/getScene/{id}") public DatasetGroup getScene(@PathVariable String id) { return dataSetGroupService.getScene(id); }}
package cn.chinatowercom.dataflow.datasource.controller;import cn.chinatowercom.dataflow.datasource.annotation.NoResultHolder;import cn.chinatowercom.dataflow.datasource.service.DataSetTableService;import cn.chinatowercom.dataflow.datasource.service.VAuthModelService;import com.strongdata.dataflow.core.datasource.entity.DataSetDetail;import com.strongdata.dataflow.core.datasource.entity.DatasetTable;import com.strongdata.dataflow.core.datasource.entity.ResultHolder;import com.strongdata.dataflow.core.datasource.entity.TableField;import com.strongdata.dataflow.core.datasource.entity.dto.DataSetTableDTO;import com.strongdata.dataflow.core.datasource.entity.dto.VAuthModelDTO;import com.strongdata.dataflow.core.datasource.entity.request.DataSetExportRequest;import com.strongdata.dataflow.core.datasource.entity.request.DataSetTableRequest;import com.strongdata.dataflow.core.datasource.entity.response.RdpResult;import com.strongdata.dataflow.core.datasource.exception.DataManageException;import com.strongdata.dataflow.core.security.annotation.NoAuth;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import io.swagger.annotations.ApiParam;import net.sf.jsqlparser.JSQLParserException;import org.springframework.web.bind.annotation.*;import javax.annotation.Resource;import javax.servlet.http.HttpServletResponse;import java.util.List;import java.util.Map;import java.util.stream.Collectors;/** * @Author gin * @Date 2023/2/20 8:29 下午 */@Api(tags = "数据集:数据集表")@RestController@RequestMapping("dataset/table")@NoAuth(value = false)public class DataSetTableController { @Resource private DataSetTableService dataSetTableService; @Resource private VAuthModelService vAuthModelService; @ApiOperation("批量保存") @PostMapping("batchAdd") public List<VAuthModelDTO> batchAdd(@RequestBody List<DataSetTableRequest> datasetTable) throws DataManageException, JSQLParserException { List<String> ids = dataSetTableService.batchInsert(datasetTable).stream().map(DatasetTable::getId).collect(Collectors.toList()); return vAuthModelService.queryAuthModelByIds("dataset", ids); } @ApiOperation("修改") @PostMapping("alter") public void alter(@RequestBody DataSetTableRequest request) throws DataManageException { dataSetTableService.alter(request); } @ApiOperation("删除") @PostMapping("delete/{id}") public void delete(@ApiParam(name = "id", value = "数据集ID", required = true) @PathVariable String id) throws DataManageException { dataSetTableService.delete(id); } @ApiOperation("查询") @PostMapping("list") public List<DataSetTableDTO> list(@RequestBody DataSetTableRequest dataSetTableRequest) { return dataSetTableService.list(dataSetTableRequest); } @ApiOperation("带权限查询") @PostMapping("getWithPermission/{id}") public DataSetTableDTO getWithPermission(@PathVariable String id) { return dataSetTableService.getWithPermission(id, null); } @ApiOperation("查询原始字段") @PostMapping("getFields") public List<TableField> getFields(@RequestBody DatasetTable datasetTable) throws DataManageException { return dataSetTableService.getFields(datasetTable); } @ApiOperation("查询预览数据") @PostMapping("getPreviewData/{page}/{pageSize}") public Map<String, Object> getPreviewData(@RequestBody DataSetTableRequest dataSetTableRequest, @PathVariable Integer page, @PathVariable Integer pageSize) throws DataManageException { return dataSetTableService.getPreviewData(dataSetTableRequest, page, pageSize, null, null); } @ApiOperation("db数据库表预览数据") @PostMapping("dbPreview") public Map<String, Object> getDBPreview(@RequestBody DataSetTableRequest dataSetTableRequest) throws DataManageException { return dataSetTableService.getDBPreview(dataSetTableRequest); } @ApiOperation("根据sql查询预览数据") @PostMapping("sqlPreview") public ResultHolder getSQLPreview(@RequestBody DataSetTableRequest dataSetTableRequest) throws DataManageException, JSQLParserException { return dataSetTableService.getSQLPreview(dataSetTableRequest); } @ApiOperation("数据集详细信息") @PostMapping("datasetDetail/{id}") public DataSetDetail datasetDetail(@PathVariable String id) { return dataSetTableService.getDatasetDetail(id); } @ApiOperation("检测doris") @PostMapping("checkDorisTableIsExists/{id}") public Boolean checkDorisTableIsExists(@PathVariable String id) throws DataManageException { return dataSetTableService.checkEngineTableIsExists(id); } @ApiOperation("数据集同步表结构") @PostMapping("syncField/{id}") public DatasetTable syncDatasetTableField(@PathVariable String id) throws DataManageException { return dataSetTableService.syncDatasetTableField(id); } @ApiOperation("根据数据集文件夹ID查询数据集名称") @PostMapping("/getDatasetNameFromGroup/{sceneId}") public List<String> getDatasetNameFromGroup(@PathVariable String sceneId) { return dataSetTableService.getDatasetNameFromGroup(sceneId); } @ApiOperation("数据集导出") @PostMapping("/exportDataset") //@I18n public void exportDataset(@RequestBody DataSetExportRequest request, HttpServletResponse response) throws DataManageException { dataSetTableService.exportDataset(request, response); } @ApiOperation("查询数据源下数据集信息") @PostMapping("/getDatasetsFromDatasource") @NoResultHolder public RdpResult getDatasetsFromDatasource(@RequestParam(value = "id") String datasourceCode) throws DataManageException { List<Map> list = dataSetTableService.getDatasetsFromDatasource(datasourceCode); return RdpResult.success(list); }}
package cn.chinatowercom.dataflow.datasource.controller;import cn.chinatowercom.dataflow.datasource.exception.DEException;import cn.chinatowercom.dataflow.datasource.service.DataSetTableFieldsService;import cn.chinatowercom.dataflow.datasource.service.DataSetTableService;import cn.chinatowercom.dataflow.datasource.service.DatasourceService;import cn.chinatowercom.dataflow.datasource.service.EngineService;import com.strongdata.dataflow.core.datasource.commons.config.ProviderFactory;import com.strongdata.dataflow.core.datasource.entity.*;import com.strongdata.dataflow.core.datasource.entity.dto.DatasetTableFieldDTO;import com.strongdata.dataflow.core.datasource.entity.request.DataSetTableRequest;import com.strongdata.dataflow.core.datasource.exception.DataManageException;import com.strongdata.dataflow.core.datasource.provider.query.QueryProvider;import com.strongdata.dataflow.core.security.annotation.NoAuth;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import org.springframework.beans.BeanUtils;import org.springframework.web.bind.annotation.*;import javax.annotation.Resource;import java.util.ArrayList;import java.util.Collections;import java.util.List;/** * @Author gin * @Date 2023/2/20 4:28 下午 */@Api(tags = "数据集:数据集字段")@RestController@RequestMapping("/dataset/field")@NoAuth(value = false)public class DataSetTableFieldController { @Resource private DataSetTableFieldsService dataSetTableFieldsService; @Resource private DataSetTableService dataSetTableService; @Resource private EngineService engineService; @Resource private DatasourceService datasourceService; @ApiOperation("分组查询表下属字段") @PostMapping("listByDQ/{tableId}") public DatasetTableField4Type listByDQ(@PathVariable String tableId) { DatasetTableField datasetTableField = DatasetTableField.builder().build(); datasetTableField.setTableId(tableId); datasetTableField.setGroupType("d"); List<DatasetTableFieldDTO> dimensionList = new ArrayList<>(); dataSetTableFieldsService.list(datasetTableField).forEach(o -> { DatasetTableFieldDTO datasetTableFieldDTO = new DatasetTableFieldDTO(); BeanUtils.copyProperties(o, datasetTableFieldDTO); List<Object> deTypeCascader = new ArrayList<>(); deTypeCascader.add(datasetTableFieldDTO.getDeType()); if (datasetTableFieldDTO.getDeExtractType() == 0 && datasetTableFieldDTO.getDeType() == 1) { deTypeCascader.add(datasetTableFieldDTO.getDateFormatType()); } datasetTableFieldDTO.setDeTypeCascader(deTypeCascader); dimensionList.add(datasetTableFieldDTO); }); datasetTableField.setGroupType("q"); List<DatasetTableFieldDTO> quotaList = new ArrayList<>(); dataSetTableFieldsService.list(datasetTableField).forEach(o -> { DatasetTableFieldDTO datasetTableFieldDTO = new DatasetTableFieldDTO(); BeanUtils.copyProperties(o, datasetTableFieldDTO); List<Object> deTypeCascader = new ArrayList<>(); deTypeCascader.add(datasetTableFieldDTO.getDeType()); if (datasetTableFieldDTO.getDeExtractType() == 0 && datasetTableFieldDTO.getDeType() == 1) { deTypeCascader.add(datasetTableFieldDTO.getDateFormatType()); } datasetTableFieldDTO.setDeTypeCascader(deTypeCascader); dimensionList.add(datasetTableFieldDTO); }); DatasetTableField4Type datasetTableField4Type = new DatasetTableField4Type(); datasetTableField4Type.setDimensionList(dimensionList); datasetTableField4Type.setQuotaList(quotaList); return datasetTableField4Type; } @ApiOperation("保存") @PostMapping("save") public DatasetTableField save(@RequestBody DatasetTableField datasetTableField) throws DataManageException { dataSetTableFieldsService.checkFieldName(datasetTableField); // 非直连数据集需先完成数据同步 DatasetTable datasetTable = dataSetTableService.get(datasetTableField.getTableId()); if (datasetTable.getMode() == 1 && !dataSetTableService.checkEngineTableIsExists(datasetTableField.getTableId())) { throw DataManageException.getException("请先完成数据同步"); } try { // 执行一次sql,确保数据集中所有字段均能正确执行 DataSetTableRequest dataSetTableRequest = new DataSetTableRequest(); BeanUtils.copyProperties(datasetTable, dataSetTableRequest); dataSetTableService.getPreviewData(dataSetTableRequest, 1, 1, Collections.singletonList(datasetTableField), null); } catch (Exception e) { DEException.throwException("字段表达式语法错误"); } return dataSetTableFieldsService.save(datasetTableField); } @ApiOperation("删除") @PostMapping("delete/{id}/{tableId}") public void delete(@PathVariable String id, @PathVariable String tableId) { dataSetTableFieldsService.delete(id); } @ApiOperation("时间格式") @PostMapping("dateformats/{tableId}") public List<Dateformat> dateformats(@PathVariable String tableId) throws DataManageException { DatasetTable datasetTable = dataSetTableService.get(tableId); Datasource ds = datasetTable.getMode() == 0 ? datasourceService.get(datasetTable.getDataSourceId()) : engineService.getDeEngine(); QueryProvider qp = ProviderFactory.getQueryProvider(ds.getType()); return qp.dateformat(); }}
package cn.chinatowercom.dataflow.datasource.controller;import cn.chinatowercom.dataflow.datasource.annotation.NoResultHolder;import cn.chinatowercom.dataflow.datasource.service.DatasourceService;import com.google.gson.Gson;import com.google.gson.reflect.TypeToken;import com.strongdata.dataflow.core.datasource.entity.ApiDefinition;import com.strongdata.dataflow.core.datasource.entity.Datasource;import com.strongdata.dataflow.core.datasource.entity.ResultHolder;import com.strongdata.dataflow.core.datasource.entity.dto.DBTableDTO;import com.strongdata.dataflow.core.datasource.entity.dto.DatasourceDTO;import com.strongdata.dataflow.core.datasource.entity.request.DatasourceUnionRequest;import com.strongdata.dataflow.core.datasource.entity.request.UpdataDsRequest;import com.strongdata.dataflow.core.datasource.entity.response.RdpResult;import com.strongdata.dataflow.core.datasource.exception.DataManageException;import com.strongdata.dataflow.core.security.annotation.NoAuth;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import org.apache.commons.lang3.StringUtils;import org.springframework.web.bind.annotation.*;import springfox.documentation.annotations.ApiIgnore;import javax.annotation.Resource;import java.util.Collection;import java.util.List;import java.util.Map;import java.util.stream.Collectors;/** * @author hj * * @createTime 2023/02/17 17:34 */@Api(tags = "数据源:数据源管理")@RequestMapping("datasource")@RestController@NoAuth(value = false)public class DatasourceController { @Resource private DatasourceService datasourceService; @ApiOperation("新增数据源") @PostMapping("/add") public Datasource addDatasource(@RequestBody DatasourceDTO datasource) throws DataManageException { return datasourceService.addDatasource(datasource); } @ApiOperation("更新数据源") @PostMapping("/update") public void updateDatasource(@RequestBody UpdataDsRequest updataDsRequest) throws DataManageException { DatasourceDTO datasource = new DatasourceDTO(); datasource.setConfigurationEncryption(updataDsRequest.isConfigurationEncryption()); datasource.setName(updataDsRequest.getName()); datasource.setDesc(updataDsRequest.getDesc()); datasource.setConfiguration(updataDsRequest.getConfiguration()); datasource.setCreateTime(null); datasource.setType(updataDsRequest.getType()); datasource.setUpdateTime(System.currentTimeMillis()); if (StringUtils.isNotEmpty(updataDsRequest.getId())) { datasource.setId(updataDsRequest.getId()); } if (StringUtils.isNotEmpty(updataDsRequest.getCode())) { datasource.setCode(updataDsRequest.getCode()); } datasourceService.preCheckDs(datasource); if (StringUtils.isNotEmpty(updataDsRequest.getId())) { datasourceService.updateDatasource(updataDsRequest.getId(), datasource, updataDsRequest.getProjectId()); } else { datasource.setProjectId(updataDsRequest.getProjectId()); datasource.setCode(updataDsRequest.getCode()); datasourceService.insert(datasource); } } @ApiOperation("数据源类型") @GetMapping("/types") public Collection types() throws DataManageException { return datasourceService.types(); } @ApiIgnore @PostMapping("/validate") public ResultHolder validate(@RequestBody DatasourceDTO datasource) throws DataManageException { return datasourceService.validate(datasource); } @ApiOperation("验证数据源") @GetMapping("/validate/{datasourceId}") public ResultHolder validate(@PathVariable String datasourceId) { return datasourceService.validate(datasourceId); } @ApiOperation("查询当前用户数据源") @GetMapping("/list") public List<DatasourceDTO> getDatasourceList(@RequestParam(value = "projectId", required = false) String projectId) throws DataManageException { DatasourceUnionRequest request = new DatasourceUnionRequest(); // : 2023/2/17 获取当前用户 需修改 request.setUserId(String.valueOf(1)); if (null != projectId) { request.setProjectId(projectId); } return datasourceService.getDatasourceList(request); } @ApiOperation("查询数据源详情") @PostMapping("/get/{id}") public DatasourceDTO getDatasource(@PathVariable String id) throws DataManageException { return datasourceService.getDataSourceDetails(id); } @ApiOperation("查询指定类型下数据源") @GetMapping("/list/{type}") public List<DatasourceDTO> getDatasourceListByType(@PathVariable String type, @RequestParam(value = "projectId", required = false) String projectId) throws DataManageException { return getDatasourceList(projectId).stream().filter(datasourceDTO -> datasourceDTO.getType().equalsIgnoreCase(type)).collect(Collectors.toList()); } @ApiOperation("删除数据源") @PostMapping("/delete/{datasourceID}") public ResultHolder deleteDatasource(@PathVariable(value = "datasourceID") String datasourceID) throws DataManageException { ResultHolder resultHolder = datasourceService.deleteDatasource(datasourceID); return resultHolder; } @ApiOperation("查询数据源下属所有表") @PostMapping("/getTables/{id}") public List<DBTableDTO> getTables(@PathVariable String id) throws DataManageException { return datasourceService.getTables(id); } /** * oracle 获取schema * @param datasource * @return * @throws DataManageException */ @ApiIgnore @PostMapping("/getSchema") public List<String> getSchema(@RequestBody DatasourceDTO datasource) throws DataManageException { return datasourceService.getSchema(datasource); } @ApiIgnore @PostMapping("/checkApiDatasource") public ApiDefinition checkApiDatasource(@RequestBody Map<String, String> data) throws DataManageException { ApiDefinition apiDefinition = new Gson().fromJson(new String(java.util.Base64.getDecoder().decode(data.get("data"))), new TypeToken<ApiDefinition>() { }.getType()); if (data.keySet().contains("type") && data.get("type").equals("apiStructure")) { apiDefinition.setShowApiStructure(true); } return datasourceService.checkApiDatasource(apiDefinition); } @ApiOperation("查询数据源列表") @GetMapping("/getDatasourceList") @NoResultHolder public RdpResult getRdpDatasourceList(@RequestParam(value = "projectId", required = false) String projectId) throws DataManageException { DatasourceUnionRequest request = new DatasourceUnionRequest(); request.setUserId(String.valueOf(1)); if (null != projectId) { request.setProjectId(projectId); } return RdpResult.success(datasourceService.getRdpDatasourceList(request)); } @ApiOperation("查询数据集的数据源信息") @GetMapping("/getDatasourceByDataSetCode") @NoResultHolder public ResultHolder getDatasourceByDataSetCode(@RequestParam(value = "dataSetCode") String dataSetCode) { return datasourceService.getDatasetsFromDatasource(dataSetCode); }}
package cn.chinatowercom.dataflow.datasource.controller;import cn.chinatowercom.dataflow.datasource.service.DriverService;import com.strongdata.dataflow.core.datasource.entity.DeDriver;import com.strongdata.dataflow.core.datasource.entity.DeDriverDetails;import com.strongdata.dataflow.core.datasource.entity.dto.DriverDTO;import com.strongdata.dataflow.core.datasource.exception.DataManageException;import com.strongdata.dataflow.core.security.annotation.NoAuth;import io.swagger.annotations.ApiImplicitParam;import io.swagger.annotations.ApiImplicitParams;import io.swagger.annotations.ApiOperation;import org.springframework.web.bind.annotation.*;import org.springframework.web.multipart.MultipartFile;import springfox.documentation.annotations.ApiIgnore;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.net.MalformedURLException;import java.util.List;import java.util.stream.Collectors;/** * @author hj * * @createTime 2023/02/17 17:34 */@ApiIgnore@RequestMapping("driver")@RestController@NoAuth(value = false)public class DriverMgmController { @Resource private DriverService driverService; @ApiOperation("驱动列表") @PostMapping("/list") public List<DriverDTO> listDeDriver(){ return driverService.list(); } @ApiOperation("删除驱动") @PostMapping("/delete") public void delete(@RequestBody DeDriver deDriver) throws DataManageException { driverService.delete(deDriver); } @ApiOperation("查询指定类型下驱动列表") @GetMapping("/list/{type}") public List<DriverDTO> listDeDriver(@PathVariable String type) throws DataManageException { return listDeDriver().stream().filter(driverDTO -> driverDTO.getType().equalsIgnoreCase(type)).collect(Collectors.toList()); } @ApiOperation("添加驱动") @PostMapping("/save") public DeDriver save(@RequestBody DeDriver deDriver) throws DataManageException { return driverService.save(deDriver); } @ApiOperation("更新驱动") @PostMapping("/update") public DeDriver update(@RequestBody DeDriver deDriver) throws DataManageException { return driverService.update(deDriver); } @ApiOperation("驱动文件列表") @GetMapping("/listDriverDetails/{id}") public List<DeDriverDetails> listDriverDetails(@PathVariable String id) throws DataManageException { return driverService.listDriverDetails(id); } @ApiOperation("删除驱动文件") @PostMapping("/deleteDriverFile") public void deleteDriverFile(@RequestBody DeDriverDetails deDriverDetails) throws DataManageException, MalformedURLException { driverService.deleteDriverFile(deDriverDetails.getId()); } @ApiOperation("驱动文件上传") @PostMapping("file/upload") @ApiImplicitParams({ @ApiImplicitParam(name = "file", value = "文件", required = true, dataType = "MultipartFile"), @ApiImplicitParam(name = "id", value = "驱动id", required = true, dataType = "String") }) public DeDriverDetails driverFileUpload(@RequestParam("id") String id, @RequestParam("file") MultipartFile file) throws DataManageException, MalformedURLException { return driverService.saveJar(file, id); } @ApiOperation("驱动文件下载") @GetMapping("file/down") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "驱动文件id", required = true, dataType = "String") }) public void driverFileDown(@RequestParam("driverFileId") String driverFileId, HttpServletRequest request, HttpServletResponse response) { driverService.driverFileDown(driverFileId, request, response); }}
package cn.chinatowercom.dataflow.datasource.controller;import cn.chinatowercom.dataflow.datasource.service.EngineService;import com.strongdata.dataflow.core.datasource.entity.DeEngine;import com.strongdata.dataflow.core.datasource.entity.ResultHolder;import com.strongdata.dataflow.core.datasource.entity.dto.DatasourceDTO;import com.strongdata.dataflow.core.datasource.exception.DataManageException;import io.swagger.annotations.ApiOperation;import org.springframework.web.bind.annotation.*;import springfox.documentation.annotations.ApiIgnore;import javax.annotation.Resource;@ApiIgnore@RequestMapping("engine")@RestControllerpublic class EngineController { @Resource private EngineService engineService; @ApiIgnore @GetMapping("/mode") public String runMode() throws DataManageException { return engineService.mode(); } @ApiOperation("引擎信息") @GetMapping("/info") public DeEngine info() throws DataManageException{ return engineService.info(); } @ApiIgnore @PostMapping("/validate") public ResultHolder validate(@RequestBody DatasourceDTO datasource) throws DataManageException { return engineService.validate(datasource); } @ApiOperation("新增/编辑") @PostMapping("/save") public ResultHolder save(@RequestBody DeEngine engine) throws DataManageException { return engineService.save(engine); }}
package cn.chinatowercom.dataflow.datasource.controller;import cn.chinatowercom.dataflow.datasource.service.RelationService;import com.strongdata.dataflow.core.datasource.entity.dto.RelationDTO;import com.strongdata.dataflow.core.security.annotation.NoAuth;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;import java.util.List;/** * @author WiSoniC * @date 2023年3月2日15:01:05 */@Api(tags = "系统:血缘关系")@RequestMapping("/api/relation")@RestController@NoAuth(value = false)public class RelationController { @Resource private RelationService relationService; @ApiOperation("获取指定数据库的血源关系") @GetMapping("/datasource/{datasourceId}") public List<RelationDTO> getRelationForDatasource(@PathVariable String datasourceId) { // : 2023/3/1 用户信息 Long userId =1L; return relationService.getRelationForDatasource(datasourceId, userId); } @ApiOperation("获取指定数据集的血缘关系") @GetMapping("/dataset/{datasetId}") public RelationDTO getRelationForDataset(@PathVariable String datasetId) { Long userId = 1L; return relationService.getRelationForDataset(datasetId, userId); }}
package cn.chinatowercom.dataflow.datasource.controller;import cn.chinatowercom.dataflow.datasource.service.VAuthModelService;import com.strongdata.dataflow.core.datasource.entity.dto.VAuthModelDTO;import com.strongdata.dataflow.core.datasource.entity.request.VAuthModelRequest;import com.strongdata.dataflow.core.security.annotation.NoAuth;import io.swagger.annotations.Api;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;import java.util.List;/** * Author: wangjiahao * Date: 2023/3/1 * Description: */@Api(tags = "授权树:授权树模型")@RestController@RequestMapping("authModel")@NoAuth(value = false)public class VAuthModelController { @Resource private VAuthModelService vAuthModelService; @PostMapping("/queryAuthModel") public List<VAuthModelDTO> queryAuthModel(@RequestBody VAuthModelRequest request) { return vAuthModelService.queryAuthModel(request); }}
package cn.chinatowercom.dataflow.datasource.service;import com.strongdata.dataflow.core.datasource.entity.DatasetTable;import com.strongdata.dataflow.core.datasource.entity.DatasetTableFunction;import com.strongdata.dataflow.core.datasource.entity.DatasetTableFunctionExample;import com.strongdata.dataflow.core.datasource.entity.Datasource;import com.strongdata.dataflow.core.datasource.mapper.DatasetTableFunctionMapper;import org.apache.commons.lang3.StringUtils;import org.springframework.stereotype.Service;import javax.annotation.Resource;import java.util.List;/** * @Author gin * @Date 2023/2/26 11:58 上午 */@Servicepublic class DatasetFunctionService { @Resource private DatasetTableFunctionMapper datasetTableFunctionMapper; @Resource private DataSetTableService dataSetTableService; @Resource private DatasourceService datasourceService; public DatasetTableFunction get(Long id) { return datasetTableFunctionMapper.selectByPrimaryKey(id); } public List<DatasetTableFunction> list(DatasetTableFunction datasetTableFunction) { DatasetTableFunctionExample datasetTableFunctionExample = new DatasetTableFunctionExample(); DatasetTableFunctionExample.Criteria criteria = datasetTableFunctionExample.createCriteria(); if (StringUtils.isNotEmpty(datasetTableFunction.getDbType())) { criteria.andDbTypeEqualTo(datasetTableFunction.getDbType()); } datasetTableFunctionExample.setOrderByClause("name asc"); return datasetTableFunctionMapper.selectByExampleWithBLOBs(datasetTableFunctionExample); } public List<DatasetTableFunction> listByTableId(String id) { DatasetTable datasetTable = dataSetTableService.get(id); String dbType; if (datasetTable.getMode() == 0) { Datasource datasource = datasourceService.get(datasetTable.getDataSourceId()); dbType = datasource.getType(); } else { dbType = "doris"; } DatasetTableFunction datasetTableFunction = new DatasetTableFunction(); datasetTableFunction.setDbType(dbType); return list(datasetTableFunction); }}
package cn.chinatowercom.dataflow.datasource.service;import com.strongdata.dataflow.core.datasource.entity.DatasetGroup;import com.strongdata.dataflow.core.datasource.entity.DatasetGroupExample;import com.strongdata.dataflow.core.datasource.entity.DatasetTable;import com.strongdata.dataflow.core.datasource.entity.dto.DataSetGroupDTO;import com.strongdata.dataflow.core.datasource.entity.dto.DataSetTableDTO;import com.strongdata.dataflow.core.datasource.entity.request.DataSetGroupRequest;import com.strongdata.dataflow.core.datasource.entity.request.DataSetTableRequest;import com.strongdata.dataflow.core.datasource.exception.DataManageException;import com.strongdata.dataflow.core.datasource.mapper.DatasetGroupMapper;import com.strongdata.dataflow.core.datasource.mapper.ExtDataSetGroupMapper;import com.strongdata.dataflow.core.datasource.utils.BeanUtils;import com.strongdata.dataflow.core.datasource.utils.TreeUtils;import org.apache.commons.collections4.CollectionUtils;import org.apache.commons.lang3.ObjectUtils;import org.apache.commons.lang3.StringUtils;import org.springframework.context.annotation.Lazy;import org.springframework.stereotype.Service;import org.springframework.util.Assert;import javax.annotation.Resource;import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.UUID;import java.util.stream.Collectors;/** * @Author gin * @Date 2023/2/28 */@Servicepublic class DataSetGroupService { @Resource private DatasetGroupMapper datasetGroupMapper; @Resource @Lazy private DataSetTableService dataSetTableService; @Resource private ExtDataSetGroupMapper extDataSetGroupMapper; public DataSetGroupDTO save(DatasetGroup datasetGroup) throws DataManageException { checkName(datasetGroup); if (StringUtils.isEmpty(datasetGroup.getId())) { if (StringUtils.isEmpty(datasetGroup.getType())) { throw DataManageException.getException("type can not be empty"); } datasetGroup.setId(UUID.randomUUID().toString()); datasetGroup.setCreateBy("1"); datasetGroup.setCreateTime(System.currentTimeMillis()); datasetGroupMapper.insert(datasetGroup); } else { datasetGroupMapper.updateByPrimaryKeySelective(datasetGroup); } DataSetGroupDTO dataSetGroupDTO = new DataSetGroupDTO(); BeanUtils.copyBean(dataSetGroupDTO, datasetGroup); dataSetGroupDTO.setLabel(dataSetGroupDTO.getName()); return dataSetGroupDTO; } public void delete(String id) throws DataManageException { Assert.notNull(id, "id cannot be null"); DatasetGroup dg = datasetGroupMapper.selectByPrimaryKey(id); if (null == dg) { return; } List<DatasetGroup> groupList = new ArrayList<>(); //递归查询分组下的所有分组 getGroupByPid(id, groupList); groupList.add(dg); //获取分组下的所有分组 List<String> ids = groupList.stream().map(DatasetGroup::getId).collect(Collectors.toList()); //查询出分组下所有的数据集 List<DatasetTable> datasetTables = dataSetTableService.getDatasetNameFromGroups(ids); if (!datasetTables.isEmpty()) { throw DataManageException.getException("当前分组下有数据集,不能删除"); } List<String> tableIds = datasetTables.stream().map(DatasetTable::getId).collect(Collectors.toList()); ids.addAll(tableIds); //删除组 DatasetGroupExample datasetGroupExample = new DatasetGroupExample(); datasetGroupExample.createCriteria().andIdIn(ids); datasetGroupMapper.deleteByExample(datasetGroupExample); // 删除场景下的表和字段 deleteTableAndField(ids); } /** * 根据上级分组查询下级分组 * * @param id * @return */ private void getGroupByPid(String id, List<DatasetGroup> groupList) { DatasetGroupExample groupExample = new DatasetGroupExample(); groupExample.createCriteria().andPidEqualTo(id); List<DatasetGroup> list = datasetGroupMapper.selectByExample(groupExample); if (CollectionUtils.isNotEmpty(list)) {//代表有下级 for (DatasetGroup group : list) { getGroupByPid(group.getId(), groupList); //循环调用自己 } } groupList.addAll(list); } public DatasetGroup getScene(String id) { return datasetGroupMapper.selectByPrimaryKey(id); } public void deleteTableAndField(List<String> sceneIds) throws DataManageException { for (String sceneId : sceneIds) { DataSetTableRequest dataSetTableRequest = new DataSetTableRequest(); dataSetTableRequest.setSceneId(sceneId); List<DataSetTableDTO> list = dataSetTableService.list(dataSetTableRequest); for (DataSetTableDTO table : list) { dataSetTableService.delete(table.getId()); } } } public List<DataSetGroupDTO> treeNode(DataSetGroupRequest datasetGroup) { datasetGroup.setLevel(null); datasetGroup.setPid("0"); datasetGroup.setType("group"); datasetGroup.setUserId("1"); List<DataSetGroupDTO> treeInfo = extDataSetGroupMapper.search(datasetGroup); return TreeUtils.mergeTree(treeInfo); } public List<DataSetGroupDTO> tree(DataSetGroupRequest datasetGroup) { datasetGroup.setLevel(null); datasetGroup.setPid(null); datasetGroup.setUserId("1"); List<DataSetGroupDTO> treeInfo = extDataSetGroupMapper.search(datasetGroup); return TreeUtils.mergeTree(treeInfo); } public List<String> getAllId(List<DataSetGroupDTO> list, List<String> ids) { for (DataSetGroupDTO dto : list) { ids.add(dto.getId()); if (CollectionUtils.isNotEmpty(dto.getChildren())) { getAllId(dto.getChildren(), ids); } } return ids; } public void checkName(DatasetGroup datasetGroup) { DatasetGroupExample datasetGroupExample = new DatasetGroupExample(); DatasetGroupExample.Criteria criteria = datasetGroupExample.createCriteria(); if (StringUtils.isNotEmpty(datasetGroup.getPid())) { criteria.andPidEqualTo(datasetGroup.getPid()); } if (StringUtils.isNotEmpty(datasetGroup.getType())) { criteria.andTypeEqualTo(datasetGroup.getType()); } if (StringUtils.isNotEmpty(datasetGroup.getName())) { criteria.andNameEqualTo(datasetGroup.getName()); } if (StringUtils.isNotEmpty(datasetGroup.getId())) { criteria.andIdNotEqualTo(datasetGroup.getId()); } if (ObjectUtils.isNotEmpty(datasetGroup.getLevel())) { criteria.andLevelEqualTo(datasetGroup.getLevel()); } List<DatasetGroup> list = datasetGroupMapper.selectByExample(datasetGroupExample); if (CollectionUtils.isNotEmpty(list)) { throw DataManageException.getException("前数据集分组名称在该目录下面已经存在"); } } public List<DatasetGroup> getParents(String id) { List<DatasetGroup> list = new ArrayList<>(); DatasetGroup datasetGroup = datasetGroupMapper.selectByPrimaryKey(id); list.add(datasetGroup); getParent(list, datasetGroup); Collections.reverse(list); return list; } public void getParent(List<DatasetGroup> list, DatasetGroup datasetGroup) { if (ObjectUtils.isNotEmpty(datasetGroup)&&StringUtils.isNotEmpty(datasetGroup.getPid())) { DatasetGroup d = datasetGroupMapper.selectByPrimaryKey(datasetGroup.getPid()); list.add(d); getParent(list, d); } }}
package cn.chinatowercom.dataflow.datasource.service;import cn.chinatowercom.dataflow.datasource.exception.DEException;import com.strongdata.dataflow.core.datasource.entity.DatasetTableField;import com.strongdata.dataflow.core.datasource.entity.DatasetTableFieldExample;import com.strongdata.dataflow.core.datasource.mapper.DatasetTableFieldMapper;import com.strongdata.dataflow.core.datasource.utils.TableUtils;import org.apache.commons.collections4.CollectionUtils;import org.apache.commons.lang3.ObjectUtils;import org.apache.commons.lang3.StringUtils;import org.springframework.stereotype.Service;import javax.annotation.Resource;import java.util.ArrayList;import java.util.List;import java.util.UUID;/** * @Author gin * @Date 2023/2/24 2:03 下午 */@Servicepublic class DataSetTableFieldsService { @Resource private DatasetTableFieldMapper datasetTableFieldMapper; public void batchEdit(List<DatasetTableField> list) { for (DatasetTableField field : list) { save(field); } } public DatasetTableField save(DatasetTableField datasetTableField) { if (StringUtils.isEmpty(datasetTableField.getId())) { datasetTableField.setId(UUID.randomUUID().toString()); // 若dataeasename为空,则用MD5(id)作为dataeasename if (StringUtils.isEmpty(datasetTableField.getDataeaseName())) { datasetTableField.setDataeaseName(TableUtils.columnName(datasetTableField.getId())); } if (ObjectUtils.isEmpty(datasetTableField.getLastSyncTime())) { datasetTableField.setLastSyncTime(System.currentTimeMillis()); } datasetTableFieldMapper.insert(datasetTableField); } else { datasetTableFieldMapper.updateByPrimaryKeySelective(datasetTableField); } return datasetTableField; } public void checkFieldName(DatasetTableField datasetTableField) { if (StringUtils.isNotEmpty(datasetTableField.getName()) && StringUtils.isNotEmpty(datasetTableField.getTableId())) { DatasetTableFieldExample datasetTableFieldExample = new DatasetTableFieldExample(); DatasetTableFieldExample.Criteria criteria = datasetTableFieldExample.createCriteria(); criteria.andNameEqualTo(datasetTableField.getName()).andTableIdEqualTo(datasetTableField.getTableId()); if (StringUtils.isNotEmpty(datasetTableField.getId())) { criteria.andIdNotEqualTo(datasetTableField.getId()); } List<DatasetTableField> datasetTableFields = datasetTableFieldMapper.selectByExample(datasetTableFieldExample); if (CollectionUtils.isNotEmpty(datasetTableFields)) { DEException.throwException("字段名不能重复"); } } } public List<DatasetTableField> list(DatasetTableField datasetTableField) { DatasetTableFieldExample datasetTableFieldExample = new DatasetTableFieldExample(); DatasetTableFieldExample.Criteria criteria = datasetTableFieldExample.createCriteria(); if (StringUtils.isNotEmpty(datasetTableField.getTableId())) { criteria.andTableIdEqualTo(datasetTableField.getTableId()); } if (ObjectUtils.isNotEmpty(datasetTableField.getChecked())) { criteria.andCheckedEqualTo(datasetTableField.getChecked()); } if (ObjectUtils.isNotEmpty(datasetTableField.getGroupType())) { criteria.andGroupTypeEqualTo(datasetTableField.getGroupType()); } datasetTableFieldExample.setOrderByClause("column_index asc"); return datasetTableFieldMapper.selectByExample(datasetTableFieldExample); } public void deleteByTableId(String tableId) { DatasetTableFieldExample datasetTableFieldExample = new DatasetTableFieldExample(); datasetTableFieldExample.createCriteria().andTableIdEqualTo(tableId); datasetTableFieldMapper.deleteByExample(datasetTableFieldExample); } public List<DatasetTableField> getListByIds(List<String> ids) { DatasetTableFieldExample datasetTableFieldExample = new DatasetTableFieldExample(); datasetTableFieldExample.createCriteria().andIdIn(ids); return datasetTableFieldMapper.selectByExample(datasetTableFieldExample); } public DatasetTableField selectByPrimaryKey(String id) { return datasetTableFieldMapper.selectByPrimaryKey(id); } public List<DatasetTableField> getListByIdsEach(List<String> ids) { List<DatasetTableField> list = new ArrayList<>(); if (CollectionUtils.isNotEmpty(ids)) { ids.forEach(id -> list.add(datasetTableFieldMapper.selectByPrimaryKey(id))); } return list; } public List<DatasetTableField> getFieldsByTableId(String id) { DatasetTableFieldExample datasetTableFieldExample = new DatasetTableFieldExample(); datasetTableFieldExample.createCriteria().andTableIdEqualTo(id); return datasetTableFieldMapper.selectByExample(datasetTableFieldExample); } public DatasetTableField get(String id) { return datasetTableFieldMapper.selectByPrimaryKey(id); } public void delete(String id) { datasetTableFieldMapper.deleteByPrimaryKey(id); } public void updateByPrimaryKeySelective(DatasetTableField request) { datasetTableFieldMapper.updateByPrimaryKeySelective(request); } /** * 根据数据集id查询数据集字段 * * @param tableIds * @return */ public List<DatasetTableField> getFieldsByTableIds(List<String> tableIds) { DatasetTableFieldExample datasetTableFieldExample = new DatasetTableFieldExample(); datasetTableFieldExample.createCriteria().andTableIdIn(tableIds); return datasetTableFieldMapper.selectByExample(datasetTableFieldExample); }}
package cn.chinatowercom.dataflow.datasource.service;import cn.chinatowercom.dataflow.datasource.exception.DEException;import cn.chinatowercom.dataflow.datasource.provider.datasource.JdbcProvider;import com.google.gson.Gson;import com.google.gson.JsonElement;import com.google.gson.JsonObject;import com.google.gson.JsonParser;import com.google.gson.reflect.TypeToken;import com.strongdata.dataflow.core.datasource.commons.config.ProviderFactory;import com.strongdata.dataflow.core.datasource.commons.constants.DatasetType;import com.strongdata.dataflow.core.datasource.commons.constants.DatasourceTypes;import com.strongdata.dataflow.core.datasource.commons.constants.DeTypeConstants;import com.strongdata.dataflow.core.datasource.entity.*;import com.strongdata.dataflow.core.datasource.entity.dto.*;import com.strongdata.dataflow.core.datasource.entity.request.DataSetExportRequest;import com.strongdata.dataflow.core.datasource.entity.request.DataSetGroupRequest;import com.strongdata.dataflow.core.datasource.entity.request.DataSetTableRequest;import com.strongdata.dataflow.core.datasource.entity.request.DatasourceRequest;import com.strongdata.dataflow.core.datasource.entity.response.DataSetPreviewPage;import com.strongdata.dataflow.core.datasource.exception.DataManageException;import com.strongdata.dataflow.core.datasource.mapper.*;import com.strongdata.dataflow.core.datasource.provider.DDLProvider;import com.strongdata.dataflow.core.datasource.provider.Provider;import com.strongdata.dataflow.core.datasource.provider.query.QueryProvider;import com.strongdata.dataflow.core.datasource.utils.BeanUtils;import com.strongdata.dataflow.core.datasource.utils.ChartDataBuild;import com.strongdata.dataflow.core.datasource.utils.CommonBeanFactory;import com.strongdata.dataflow.core.datasource.utils.TableUtils;import lombok.extern.slf4j.Slf4j;import net.sf.jsqlparser.JSQLParserException;import net.sf.jsqlparser.expression.Alias;import net.sf.jsqlparser.expression.BinaryExpression;import net.sf.jsqlparser.expression.Expression;import net.sf.jsqlparser.expression.Parenthesis;import net.sf.jsqlparser.expression.operators.conditional.AndExpression;import net.sf.jsqlparser.expression.operators.conditional.OrExpression;import net.sf.jsqlparser.expression.operators.relational.*;import net.sf.jsqlparser.parser.CCJSqlParserUtil;import net.sf.jsqlparser.statement.Statement;import net.sf.jsqlparser.statement.select.*;import net.sf.jsqlparser.util.deparser.ExpressionDeParser;import org.apache.commons.collections4.CollectionUtils;import org.apache.commons.lang3.ObjectUtils;import org.apache.commons.lang3.StringUtils;import org.apache.poi.ss.usermodel.*;import org.apache.poi.xssf.usermodel.XSSFWorkbook;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import javax.annotation.Resource;import javax.servlet.http.HttpServletResponse;import java.io.OutputStream;import java.text.MessageFormat;import java.util.*;import java.util.regex.Matcher;import java.util.regex.Pattern;import java.util.stream.Collectors;/** * @Author gin * @Date 2023/2/23 2:54 下午 */@Service@Transactional(rollbackFor = Exception.class)@Slf4jpublic class DataSetTableService { private final static String DEFINE_CN_DATA_DELETED = "当前用到的数据源已被删除"; private final static String DEFINE_CN_DATASOURCE_NOT_FOUND_COLUMN = "当前关联数据集,无选中字段,请重新编辑"; private final static String DEFINE_CN_NAME_USED = "同一分组下该名称已被使用"; private final static String DEFINE_CN_DATASOURCE_INVALID = "无效数据源"; private final static String DEFINE_GROUP = "group"; private final static String DEFINE_FIELDS = "fields"; private final static String DEFINE_ERROR = "Error"; private final static String DEFINE_CN_EXEC_SQL_FAIL = "预览数据错误:执行SQL失败。可能因相关字段、表、数据集等元素发生变更,请检查"; private final static String DEFINE_CN_DATASOURCE_DELETED = "自定义数据集所关联数据被删除,无法正常显示"; private final static String DEFINE_TABLE_ID = ":table id [%s]"; private final static String DEFINE_SPACE_AND_SPACE = " AND "; private final static String DEFINE_SELECT_FROM = "SELECT {0} FROM {1}"; private final static String DEFINE_FIELD = "field"; private static final Logger logger = LoggerFactory.getLogger(DataSetTableService.class); @Resource private DatasetTableMapper datasetTableMapper; @Resource private DatasourceMapper datasourceMapper; @Resource private DataSetTableFieldsService dataSetTableFieldsService; @Resource private ExtractDataService extractDataService; @Resource private ExtDataSetTableMapper extDataSetTableMapper; @Resource private ExtDataSetGroupMapper extDataSetGroupMapper; @Resource private DatasetTableFieldMapper datasetTableFieldMapper; @Resource private EngineService engineService; @Resource private DatasourceService datasourceService;// private static boolean isUpdatingDatasetTableStatus = false;// private static final String lastUpdateTime = "${__last_update_time__}";// private static final String currentUpdateTime = "${__current_update_time__}"; private static final String regex = "\\$\\{(.*?)\\}"; private static final String SubstitutedParams = "DATAEASE_PATAMS_BI"; private static final String SubstitutedSql = " 'BI' = 'BI' "; @Value("${file.root.dir}") private String rootDir; //@DeCleaner(value = DePermissionType.DATASET, key = "sceneId") public List<DatasetTable> batchInsert(List<DataSetTableRequest> datasetTable) throws DataManageException, JSQLParserException { // 保存之前校验table名称 checkNames(datasetTable); List<DatasetTable> list = new ArrayList<>(); for (DataSetTableRequest table : datasetTable) { list.add(save(table)); } return list; } private void extractData(DataSetTableRequest datasetTable) throws DataManageException { if (datasetTable.getMode() == 1 && StringUtils.isNotEmpty(datasetTable.getSyncType()) && datasetTable.getSyncType().equalsIgnoreCase("sync_now")) { // : 2023/3/15 修改建立数据集后的将建立数据表流程 extractDataService.extractData(datasetTable.getId(), "all_scope"); } } //@DeCleaner(value = DePermissionType.DATASET, key = "sceneId") public DatasetTable save(DataSetTableRequest datasetTable) throws DataManageException, JSQLParserException { checkNameAndCode(datasetTable); if (StringUtils.equalsIgnoreCase(datasetTable.getType(), DatasetType.SQL.name()) && !"appApply".equalsIgnoreCase(datasetTable.getOptFrom())) { DataSetTableRequest dataSetTableRequest = new DataSetTableRequest(); BeanUtils.copyBean(dataSetTableRequest, datasetTable); getSQLPreview(dataSetTableRequest); } if (StringUtils.isEmpty(datasetTable.getId())) { datasetTable.setId(UUID.randomUUID().toString()); datasetTable.setCreateBy("1"); datasetTable.setCreateTime(System.currentTimeMillis()); int insert = datasetTableMapper.insert(datasetTable); // 添加表成功后,获取当前表字段和类型,抽象到dataease数据库 if (insert == 1) { if (datasetTable.getOptFrom() == null || !"appApply".equalsIgnoreCase(datasetTable.getOptFrom())) { saveTableField(datasetTable); } extractData(datasetTable);} } else { int update = datasetTableMapper.updateByPrimaryKeySelective(datasetTable); if ((datasetTable.getIsRename() == null || !datasetTable.getIsRename()) && update == 1) { // 更新数据和字段 if (StringUtils.equalsIgnoreCase(datasetTable.getType(), DatasetType.SQL.name()) || StringUtils.equalsIgnoreCase(datasetTable.getType(), DatasetType.CUSTOM.name()) || StringUtils.equalsIgnoreCase(datasetTable.getType(), DatasetType.UNION.name())) { saveTableField(datasetTable); } extractData(datasetTable); } } return datasetTable; } public void alter(DataSetTableRequest request) { checkNameAndCode(request); datasetTableMapper.updateByPrimaryKeySelective(request); } public void delete(String id) { DatasetTable table = datasetTableMapper.selectByPrimaryKey(id); datasetTableMapper.deleteByPrimaryKey(id); dataSetTableFieldsService.deleteByTableId(id); try { // 抽取的数据集删除doris if (table.getMode() == 1) { deleteDorisTable(id, table); } } catch (Exception e) { logger.error(e.getMessage()); } } private void deleteDorisTable(String datasetId, DatasetTable table) throws DataManageException { String dorisTableName = TableUtils.tableName(datasetId); Datasource dorisDatasource = engineService.getDeEngine(); JdbcProvider jdbcProvider = CommonBeanFactory.getBean(JdbcProvider.class); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(dorisDatasource); DDLProvider ddlProvider = ProviderFactory.getDDLProvider(dorisDatasource.getType()); if (StringUtils.equalsIgnoreCase(DatasetType.CUSTOM.name(), table.getType()) || StringUtils.equalsIgnoreCase(DatasetType.UNION.name(), table.getType())) { datasourceRequest.setQuery(ddlProvider.dropView(dorisTableName)); jdbcProvider.exec(datasourceRequest); datasourceRequest.setQuery(ddlProvider.dropView(TableUtils.tmpName(dorisTableName))); jdbcProvider.exec(datasourceRequest); } else { datasourceRequest.setQuery(ddlProvider.dropTable(dorisTableName)); jdbcProvider.exec(datasourceRequest); datasourceRequest.setQuery(ddlProvider.dropTable(TableUtils.tmpName(dorisTableName))); jdbcProvider.exec(datasourceRequest); } } public List<String> getDatasetNameFromGroup(String sceneId) { DatasetTableExample example = new DatasetTableExample(); example.createCriteria().andSceneIdEqualTo(sceneId); List<DatasetTable> datasetTables = datasetTableMapper.selectByExample(example); return datasetTables.stream().map(DatasetTable::getName).collect(Collectors.toList()); } /** * 查询分组下所有数据集 * * @param stringList * @return */ public List<DatasetTable> getDatasetNameFromGroups(List<String> stringList) { DatasetTableExample example = new DatasetTableExample(); example.createCriteria().andSceneIdIn(stringList); List<DatasetTable> datasetTables = datasetTableMapper.selectByExample(example); return datasetTables; } public List<DataSetTableDTO> list(DataSetTableRequest dataSetTableRequest) { dataSetTableRequest.setUserId("1"); dataSetTableRequest.setTypeFilter(dataSetTableRequest.getTypeFilter()); return extDataSetTableMapper.search(dataSetTableRequest); } public List<DatasetTable> list(List<String> datasetIds) { DatasetTableExample example = new DatasetTableExample(); example.createCriteria().andIdIn(datasetIds); return datasetTableMapper.selectByExample(example); } public List<DataSetTableDTO> listAndGroup(DataSetTableRequest dataSetTableRequest) { dataSetTableRequest.setUserId("1"); dataSetTableRequest.setTypeFilter(dataSetTableRequest.getTypeFilter()); List<DataSetTableDTO> ds = extDataSetTableMapper.search(dataSetTableRequest); ds.forEach(ele -> ele.setIsLeaf(true)); // 获取group下的子group DataSetGroupRequest datasetGroup = new DataSetGroupRequest(); datasetGroup.setLevel(null); datasetGroup.setType(DEFINE_GROUP); datasetGroup.setPid(dataSetTableRequest.getSceneId()); datasetGroup.setUserId("1"); datasetGroup.setSort("name asc,create_time desc"); List<DataSetGroupDTO> groups = extDataSetGroupMapper.search(datasetGroup); List<DataSetTableDTO> group = groups.stream().map(ele -> { DataSetTableDTO dto = new DataSetTableDTO(); BeanUtils.copyBean(dto, ele); dto.setIsLeaf(false); dto.setType(DEFINE_GROUP); return dto; }).collect(Collectors.toList()); group.addAll(ds); return group; } public List<DataSetTableDTO> search(DataSetTableRequest dataSetTableRequest) { // : 2023/2/17 获取当前用户 String userId = "1"; dataSetTableRequest.setUserId(userId); dataSetTableRequest.setSort("name asc"); List<DataSetTableDTO> ds = extDataSetTableMapper.search(dataSetTableRequest); if (CollectionUtils.isEmpty(ds)) { return ds; } TreeSet<String> ids = new TreeSet<>(); ds.forEach(ele -> { ele.setIsLeaf(true); ele.setPid(ele.getSceneId()); ids.add(ele.getPid()); }); List<DataSetTableDTO> group = new ArrayList<>(); DataSetGroupRequest dataSetGroupRequest = new DataSetGroupRequest(); dataSetGroupRequest.setUserId(userId); dataSetGroupRequest.setIds(ids); List<DataSetGroupDTO> search = extDataSetGroupMapper.search(dataSetGroupRequest); while (CollectionUtils.isNotEmpty(search)) { ids.clear(); search.forEach(ele -> { DataSetTableDTO dto = new DataSetTableDTO(); BeanUtils.copyBean(dto, ele); dto.setIsLeaf(false); dto.setType(DEFINE_GROUP); group.add(dto); ids.add(ele.getPid()); }); dataSetGroupRequest.setIds(ids); search = extDataSetGroupMapper.search(dataSetGroupRequest); } List<DataSetTableDTO> res = new ArrayList<>(); Map<String, DataSetTableDTO> map = new TreeMap<>(); group.forEach(ele -> map.put(ele.getId(), ele)); for (Map.Entry<String, DataSetTableDTO> stringDataSetTableDTOEntry : map.entrySet()) { res.add(stringDataSetTableDTOEntry.getValue()); } res.sort(Comparator.comparing(DatasetTable::getName)); res.addAll(ds); return res; } public DatasetTable get(String id) { return datasetTableMapper.selectByPrimaryKey(id); } public DataSetTableDTO getWithPermission(String id, Long user) { logger.debug("{}", user); Long userId = 1L; DataSetTableRequest dataSetTableRequest = new DataSetTableRequest(); dataSetTableRequest.setId(id); dataSetTableRequest.setUserId(String.valueOf(userId)); dataSetTableRequest.setTypeFilter(dataSetTableRequest.getTypeFilter()); return extDataSetTableMapper.searchOne(dataSetTableRequest); } public List<TableField> getFields(DatasetTable datasetTable) throws DataManageException { Datasource ds = datasourceMapper.selectByPrimaryKey(datasetTable.getDataSourceId()); Provider datasourceProvider = ProviderFactory.getProvider(ds.getType()); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(ds); datasourceRequest.setTable(new Gson().fromJson(datasetTable.getInfo(), DataTableInfoDTO.class).getTable()); return datasourceProvider.getTableFields(datasourceRequest); } public List<TableFieldDTO> getApiFields(DatasetTable datasetTable) throws DataManageException { Datasource ds = datasourceMapper.selectByPrimaryKey(datasetTable.getDataSourceId()); Provider datasourceProvider = ProviderFactory.getProvider(ds.getType()); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(ds); datasourceRequest.setTable(new Gson().fromJson(datasetTable.getInfo(), DataTableInfoDTO.class).getTable()); List<TableField> tableFields = datasourceProvider.getTableFields(datasourceRequest); List<TableFieldDTO> fieldDTOList = new ArrayList<>(); tableFields.forEach(tableField -> { TableFieldDTO dto = new TableFieldDTO(); dto.setColumnName(tableField.getFieldName()); dto.setColumnType(tableField.getFieldType()); dto.setColumnComments(tableField.getRemarks()); fieldDTOList.add(dto); }); return fieldDTOList; } public Map<String, List<DatasetTableField>> getFieldsFromDE(DataSetTableRequest dataSetTableRequest) { DatasetTableField datasetTableField = DatasetTableField.builder().build(); datasetTableField.setTableId(dataSetTableRequest.getId()); datasetTableField.setChecked(Boolean.TRUE); List<DatasetTableField> fields = dataSetTableFieldsService.list(datasetTableField); List<DatasetTableField> dimension = new ArrayList<>(); List<DatasetTableField> quota = new ArrayList<>(); fields.forEach(field -> { if (StringUtils.equalsIgnoreCase("q", field.getGroupType())) { quota.add(field); } else { dimension.add(field); } }); // quota add count DatasetTableField count = DatasetTableField.builder() .id("count") .tableId(dataSetTableRequest.getId()) .originName("*") .name("记录数*") .dataeaseName("*") .type("INT") .checked(true) .columnIndex(999) .deType(2) .extField(1) .groupType("q") .build(); quota.add(count); Map<String, List<DatasetTableField>> map = new HashMap<>(); map.put("dimension", dimension); map.put("quota", quota); return map; } public Map<String, Object> getPreviewData(DataSetTableRequest dataSetTableRequest, Integer page, Integer pageSize, List<DatasetTableField> extFields, DatasetRowPermissionsTreeObj extTree) throws DataManageException { log.debug(extTree.toString()); Map<String, Object> map = new HashMap<>(); String syncStatus = ""; DatasetTableField datasetTableField = DatasetTableField.builder().tableId(dataSetTableRequest.getId()) .checked(Boolean.TRUE).build(); List<DatasetTableField> fields = dataSetTableFieldsService.list(datasetTableField); if (CollectionUtils.isNotEmpty(extFields)) { fields = extFields; } if (CollectionUtils.isEmpty(fields)) { map.put(DEFINE_FIELDS, fields); map.put("data", new ArrayList<>()); map.put("page", new DataSetPreviewPage()); return map; } DatasetTable datasetTable = datasetTableMapper.selectByPrimaryKey(dataSetTableRequest.getId()); Map<String, ColumnPermissionItem> desensitizationList = new HashMap<>(); String[] fieldArray = fields.stream().map(DatasetTableField::getDataeaseName).toArray(String[]::new); DataTableInfoDTO dataTableInfoDTO = new Gson().fromJson(dataSetTableRequest.getInfo(), DataTableInfoDTO.class); List<String[]> data = new ArrayList<>(); DataSetPreviewPage dataSetPreviewPage = new DataSetPreviewPage(); dataSetPreviewPage.setShow(Integer.valueOf(dataSetTableRequest.getRow())); dataSetPreviewPage.setPage(page); dataSetPreviewPage.setPageSize(pageSize); int realSize = Integer.parseInt(dataSetTableRequest.getRow()) < pageSize ? Integer.parseInt(dataSetTableRequest.getRow()) : pageSize; if (page == Integer.parseInt(dataSetTableRequest.getRow()) / pageSize + 1) { realSize = Integer.parseInt(dataSetTableRequest.getRow()) % pageSize; } if (StringUtils.equalsIgnoreCase(datasetTable.getType(), DatasetType.DB.name()) || StringUtils.equalsIgnoreCase(datasetTable.getType(), DatasetType.API.name())) { if (datasetTable.getMode() == 0) { Datasource ds = datasourceMapper.selectByPrimaryKey(dataSetTableRequest.getDataSourceId()); if (ObjectUtils.isEmpty(ds)) { throw DataManageException.getException(DEFINE_CN_DATA_DELETED); } if (StringUtils.isNotEmpty(ds.getStatus()) && ds.getStatus().equalsIgnoreCase(DEFINE_ERROR)) { throw DataManageException.getException(DEFINE_CN_DATASOURCE_INVALID); } Provider datasourceProvider = ProviderFactory.getProvider(ds.getType()); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(ds); String table = dataTableInfoDTO.getTable(); QueryProvider qp = ProviderFactory.getQueryProvider(ds.getType()); datasourceRequest.setQuery( qp.createQueryTableWithPage(table, fields, page, pageSize, realSize, false, ds, null, null)); map.put("sql", Base64.getEncoder().encodeToString(datasourceRequest.getQuery().getBytes())); datasourceRequest.setPage(page); datasourceRequest.setFetchSize(Integer.parseInt(dataSetTableRequest.getRow())); datasourceRequest.setPageSize(pageSize); datasourceRequest.setRealSize(realSize); datasourceRequest.setPreviewData(true); try { datasourceRequest.setPageable(true); data.addAll(datasourceProvider.getData(datasourceRequest)); } catch (Exception e) { logger.error(e.getMessage()); DEException.throwException(DEFINE_CN_EXEC_SQL_FAIL + "->" + e.getMessage()); } try { datasourceRequest.setQuery(qp.createQueryTableWithLimit(table, fields, Integer.valueOf(dataSetTableRequest.getRow()), false, ds, null, null)); datasourceRequest.setPageable(false); dataSetPreviewPage.setTotal(datasourceProvider.getData(datasourceRequest).size()); } catch (Exception e) { logger.error(e.getMessage()); DEException.throwException(DEFINE_CN_EXEC_SQL_FAIL + "->" + e.getMessage()); } } else { // check doris table if (!checkEngineTableIsExists(dataSetTableRequest.getId())) { if (dataSetTableRequest.isPreviewForTask()) { map.put(DEFINE_FIELDS, fields); map.put("data", new ArrayList<>()); map.put("page", new DataSetPreviewPage()); return map; } else { throw DataManageException.getException("请先完成数据同步"); } } Datasource ds = engineService.getDeEngine(); JdbcProvider jdbcProvider = CommonBeanFactory.getBean(JdbcProvider.class); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(ds); String table = TableUtils.tableName(dataSetTableRequest.getId()); QueryProvider qp = ProviderFactory.getQueryProvider(ds.getType()); datasourceRequest.setQuery( qp.createQueryTableWithPage(table, fields, page, pageSize, realSize, false, ds, null, null)); map.put("sql", Base64.getEncoder().encodeToString(datasourceRequest.getQuery().getBytes())); try { data.addAll(jdbcProvider.getData(datasourceRequest)); } catch (Exception e) { logger.error(e.getMessage()); DEException.throwException(DEFINE_CN_EXEC_SQL_FAIL + "->" + e.getMessage()); } try { datasourceRequest.setQuery(qp.createQueryTableWithLimit(table, fields, Integer.valueOf(dataSetTableRequest.getRow()), false, ds, null, null)); dataSetPreviewPage.setTotal(jdbcProvider.getData(datasourceRequest).size()); } catch (Exception e) { logger.error(e.getMessage()); DEException.throwException(DEFINE_CN_EXEC_SQL_FAIL + "->" + e.getMessage()); } } } else if (StringUtils.equalsIgnoreCase(datasetTable.getType(), DatasetType.SQL.name())) { if (datasetTable.getMode() == 0) { Datasource ds = datasourceMapper.selectByPrimaryKey(dataSetTableRequest.getDataSourceId()); if (ObjectUtils.isEmpty(ds)) { throw DataManageException.getException(DEFINE_CN_DATA_DELETED); } if (StringUtils.isNotEmpty(ds.getStatus()) && ds.getStatus().equalsIgnoreCase(DEFINE_ERROR)) { throw DataManageException.getException(DEFINE_CN_DATASOURCE_INVALID); } Provider datasourceProvider = ProviderFactory.getProvider(ds.getType()); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(ds); DataTableInfoDTO dataTableInfo = new Gson().fromJson(datasetTable.getInfo(), DataTableInfoDTO.class); String sql = dataTableInfo.isBase64Encryption() ? new String(Base64.getDecoder().decode(dataTableInfo.getSql())) : dataTableInfo.getSql(); sql = handleVariableDefaultValue(sql, null, ds.getType()); QueryProvider qp = ProviderFactory.getQueryProvider(ds.getType()); datasourceRequest.setQuery( qp.createQuerySQLWithPage(sql, fields, page, pageSize, realSize, false, null, null)); map.put("sql", Base64.getEncoder().encodeToString(datasourceRequest.getQuery().getBytes())); datasourceRequest.setPage(page); datasourceRequest.setFetchSize(Integer.parseInt(dataSetTableRequest.getRow())); datasourceRequest.setPageSize(pageSize); datasourceRequest.setRealSize(realSize); datasourceRequest.setPreviewData(true); try { datasourceRequest.setPageable(true); //datasourceRequest.setPermissionFields(fields); data.addAll(datasourceProvider.getData(datasourceRequest)); } catch (Exception e) { logger.error(e.getMessage()); DEException.throwException(DEFINE_CN_EXEC_SQL_FAIL + "->" + e.getMessage()); } try { datasourceRequest.setPageable(false); datasourceRequest.setQuery(qp.createQuerySqlWithLimit(sql, fields, Integer.valueOf(dataSetTableRequest.getRow()), false, null, null)); dataSetPreviewPage.setTotal(datasourceProvider.getData(datasourceRequest).size()); } catch (Exception e) { logger.error(e.getMessage()); DEException.throwException(DEFINE_CN_EXEC_SQL_FAIL + "->" + e.getMessage()); } } else { // check doris table if (!checkEngineTableIsExists(dataSetTableRequest.getId())) { throw DataManageException.getException("请先完成数据同步"); } Datasource ds = engineService.getDeEngine(); JdbcProvider jdbcProvider = CommonBeanFactory.getBean(JdbcProvider.class); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(ds); String table = TableUtils.tableName(dataSetTableRequest.getId()); QueryProvider qp = ProviderFactory.getQueryProvider(ds.getType()); datasourceRequest.setQuery( qp.createQueryTableWithPage(table, fields, page, pageSize, realSize, false, ds, null, null)); map.put("sql", Base64.getEncoder().encodeToString(datasourceRequest.getQuery().getBytes())); try { data.addAll(jdbcProvider.getData(datasourceRequest)); } catch (Exception e) { logger.error(e.getMessage()); DEException.throwException(DEFINE_CN_EXEC_SQL_FAIL + "->" + e.getMessage()); } try { datasourceRequest.setQuery(qp.createQueryTableWithLimit(table, fields, Integer.valueOf(dataSetTableRequest.getRow()), false, ds, null, null)); dataSetPreviewPage.setTotal(jdbcProvider.getData(datasourceRequest).size()); } catch (Exception e) { logger.error(e.getMessage()); DEException.throwException(DEFINE_CN_EXEC_SQL_FAIL + "->" + e.getMessage()); } } } List<Map<String, Object>> jsonArray = new ArrayList<>(); if (CollectionUtils.isNotEmpty(data)) { jsonArray = data.stream().map(ele -> { Map<String, Object> tmpMap = new HashMap<>(); for (int i = 0; i < ele.length; i++) { if (desensitizationList.keySet().contains(fieldArray[i])) { tmpMap.put(fieldArray[i], ChartDataBuild.desensitizationValue(desensitizationList.get(fieldArray[i]), String.valueOf(ele[i]))); } else { tmpMap.put(fieldArray[i], ele[i]); } } return tmpMap; }).collect(Collectors.toList()); } if (!map.containsKey("status")) { map.put("status", "success"); } map.put(DEFINE_FIELDS, fields); map.put("data", jsonArray); map.put("page", dataSetPreviewPage); map.put("syncStatus", syncStatus); return map; }// private List<SqlVariableDetails> getSqlVariableDetails(String type, List<DatasetTable> datasetTables) {// List<SqlVariableDetails> sqlVariableDetails = new ArrayList<>();// for (DatasetTable datasetTable : datasetTables) {// if (StringUtils.isNotEmpty(datasetTable.getSqlVariableDetails())) {// List<SqlVariableDetails> sqlVariables = new Gson().fromJson(datasetTable.getSqlVariableDetails(), new TypeToken<List<SqlVariableDetails>>() {// }.getType());// for (SqlVariableDetails sqlVariable : sqlVariables) {// sqlVariable.setId(datasetTable.getId() + "|DE|" + sqlVariable.getVariableName());// sqlVariable.setVariableName("[" + datasetTable.getName() + "]-" + sqlVariable.getVariableName());// sqlVariableDetails.add(sqlVariable);// }// }// }//// switch (type) {// case "DATE":// sqlVariableDetails = sqlVariableDetails.stream().filter(item -> item.getType().get(0).contains("DATETIME")).collect(Collectors.toList());// sqlVariableDetails.forEach(item -> {// if (item.getType().size() > 1) {// item.setAlias(item.getVariableName() + "[" + item.getType().get(1) + "]");// } else {// item.setAlias(item.getVariableName());// }// });// break;// case "TEXT":// sqlVariableDetails = sqlVariableDetails.stream().filter(item -> item.getType().get(0).contains("TEXT")).collect(Collectors.toList());// sqlVariableDetails.forEach(item -> item.setAlias(item.getVariableName()));// break;// case "NUM":// sqlVariableDetails = sqlVariableDetails.stream().filter(item -> item.getType().get(0).contains("LONG") || item.getType().get(0).contains("DOUBLE")).collect(Collectors.toList());// sqlVariableDetails.forEach(item -> item.setAlias(item.getVariableName()));// break;// }// return sqlVariableDetails;// } public void checkVariable(final String sql, String dsType) throws DataManageException, JSQLParserException { String tmpSql = removeVariables(sql, dsType); if (tmpSql.contains(SubstitutedParams)) { throw DataManageException.getException("SQL 变量只能在 WHERE 条件中使用"); } } public String handleVariableDefaultValue(String sql, String sqlVariableDetails, String dsType) { if (StringUtils.isEmpty(sql)) { DataManageException.throwException("SQL 不能为空"); } if (sqlVariableDetails != null) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(sql); while (matcher.find()) { SqlVariableDetails defaultsSqlVariableDetail = null; List<SqlVariableDetails> defaultsSqlVariableDetails = new Gson().fromJson(sqlVariableDetails, new TypeToken<List<SqlVariableDetails>>() { }.getType()); for (SqlVariableDetails sqlVariableDetail : defaultsSqlVariableDetails) { if (matcher.group().substring(2, matcher.group().length() - 1).equalsIgnoreCase(sqlVariableDetail.getVariableName())) { defaultsSqlVariableDetail = sqlVariableDetail; break; } } if (defaultsSqlVariableDetail != null && StringUtils.isNotEmpty(defaultsSqlVariableDetail.getDefaultValue())) { sql = sql.replace(matcher.group(), defaultsSqlVariableDetail.getDefaultValue()); } } } try { sql = removeVariables(sql, dsType); } catch (Exception e) { logger.error(e.getMessage()); } return sql; } public String removeVariables(final String sql, String dsType) throws DataManageException, JSQLParserException { String tmpSql = sql; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(tmpSql); boolean hasVariables = false; while (matcher.find()) { hasVariables = true; tmpSql = tmpSql.replace(matcher.group(), SubstitutedParams); } if (!hasVariables && !tmpSql.contains(SubstitutedParams)) { return tmpSql; } Statement statement = CCJSqlParserUtil.parse(tmpSql); Select select = (Select) statement; if (select.getSelectBody() instanceof PlainSelect) { return handlePlainSelect((PlainSelect) select.getSelectBody(), select, dsType); } else { StringBuilder result = new StringBuilder(); SetOperationList setOperationList = (SetOperationList) select.getSelectBody(); for (int i = 0; i < setOperationList.getSelects().size(); i++) { result.append(handlePlainSelect((PlainSelect) setOperationList.getSelects().get(i), null, dsType)); if (i < setOperationList.getSelects().size() - 1) { result.append(" ").append(setOperationList.getOperations().get(i).toString()).append(" "); } } return result.toString(); } } private String handlePlainSelect(PlainSelect plainSelect, Select statementSelect, String dsType) throws DataManageException, JSQLParserException { FromItem fromItem = plainSelect.getFromItem(); if (fromItem instanceof SubSelect) { SelectBody selectBody = ((SubSelect) fromItem).getSelectBody(); SubSelect subSelect = new SubSelect(); Select subSelectTmp = (Select) CCJSqlParserUtil.parse(removeVariables(selectBody.toString(), dsType)); PlainSelect subPlainSelect = ((PlainSelect) subSelectTmp.getSelectBody()); subSelect.setSelectBody(subPlainSelect); if (dsType.equals(DatasourceTypes.oracle.getType())) { subSelect.setAlias(new Alias(fromItem.getAlias().toString(), false)); } else { if (fromItem.getAlias() == null) { throw DataManageException.getException("Failed to parse sql, Every derived table must have its own alias!"); } subSelect.setAlias(new Alias(fromItem.getAlias().toString(), false)); } plainSelect.setFromItem(subSelect); } List<Join> joins = plainSelect.getJoins(); if (joins != null) { List<Join> joinsList = new ArrayList<>(); for (Join join : joins) { FromItem rightItem = join.getRightItem(); if (rightItem instanceof SubSelect) { SelectBody selectBody = ((SubSelect) rightItem).getSelectBody(); SubSelect subSelect = new SubSelect(); Select subSelectTmp = (Select) CCJSqlParserUtil.parse(removeVariables(selectBody.toString(), dsType)); PlainSelect subPlainSelect = ((PlainSelect) subSelectTmp.getSelectBody()); subSelect.setSelectBody(subPlainSelect); if (dsType.equals(DatasourceTypes.oracle.getType())) { subSelect.setAlias(new Alias(rightItem.getAlias().toString(), false)); } else { if (rightItem.getAlias() == null) { throw DataManageException.getException("Failed to parse sql, Every derived table must have its own alias!"); } subSelect.setAlias(new Alias(rightItem.getAlias().toString(), false)); } join.setRightItem(subSelect); } joinsList.add(join); } plainSelect.setJoins(joinsList); } Expression expr = plainSelect.getWhere(); if (Objects.isNull(expr)) { return handleWith(plainSelect, statementSelect, dsType); } StringBuilder stringBuilder = new StringBuilder(); BinaryExpression binaryExpression = null; try { binaryExpression = (BinaryExpression) expr; } catch (Exception e) { logger.error(e.getMessage()); } if (!Objects.isNull(binaryExpression) && !(binaryExpression.getLeftExpression() instanceof BinaryExpression) && !(binaryExpression.getRightExpression() instanceof BinaryExpression) && hasVariable(binaryExpression.toString())) { stringBuilder.append(SubstitutedSql); } else { expr.accept(getExpressionDeParser(stringBuilder)); } plainSelect.setWhere(CCJSqlParserUtil.parseCondExpression(stringBuilder.toString())); return handleWith(plainSelect, statementSelect, dsType); } private String handleWith(PlainSelect plainSelect, Select select, String dsType) throws DataManageException, JSQLParserException { StringBuilder builder = new StringBuilder(); if (select != null && CollectionUtils.isNotEmpty(select.getWithItemsList())) { builder.append("WITH"); builder.append(" "); for (Iterator<WithItem> iter = select.getWithItemsList().iterator(); iter.hasNext(); ) { WithItem withItem = iter.next(); builder.append(withItem.getName()).append(" AS ( ").append(removeVariables(withItem.getSubSelect().toString(), dsType)).append(" ) "); if (iter.hasNext()) { builder.append(","); } } } builder.append(" ").append(plainSelect); return builder.toString(); } public Map<String, Object> getDBPreview(DataSetTableRequest dataSetTableRequest) throws DataManageException { Datasource ds = datasourceMapper.selectByPrimaryKey(dataSetTableRequest.getDataSourceId()); if (ds == null) { throw DataManageException.getException(DEFINE_CN_DATASOURCE_INVALID); } Provider datasourceProvider = ProviderFactory.getProvider(ds.getType()); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(ds); DataTableInfoDTO dataTableInfo = new Gson().fromJson(dataSetTableRequest.getInfo(), DataTableInfoDTO.class); QueryProvider qp = ProviderFactory.getQueryProvider(ds.getType()); String sqlAsTable = qp.createSQLPreview(qp.sqlForPreview(dataTableInfo.getTable(), ds), null); datasourceRequest.setQuery(sqlAsTable); datasourceRequest.setTable(dataTableInfo.getTable()); Map<String, List> result = datasourceProvider.fetchResultAndField(datasourceRequest); List<String[]> data = result.get("dataList"); List<TableField> fields = result.get("fieldList"); String[] fieldArray = fields.stream().map(TableField::getFieldName).toArray(String[]::new); if (checkIsRepeat(fieldArray)) { DataManageException.throwException("存在重复字段,请修改后重试"); } List<Map<String, Object>> jsonArray = new ArrayList<>(); if (CollectionUtils.isNotEmpty(data)) { jsonArray = data.stream().map(ele -> { Map<String, Object> map = new HashMap<>(); for (int i = 0; i < ele.length; i++) { map.put(fieldArray[i], ele[i]); } return map; }).collect(Collectors.toList()); } Map<String, Object> map = new HashMap<>(); map.put(DEFINE_FIELDS, fields); map.put("data", jsonArray); return map; } public ResultHolder getSQLPreview(DataSetTableRequest dataSetTableRequest) throws DataManageException, JSQLParserException { DatasetSqlLog datasetSqlLog = new DatasetSqlLog(); DataTableInfoDTO dataTableInfo = new Gson().fromJson(dataSetTableRequest.getInfo(), DataTableInfoDTO.class); String sql = dataTableInfo.isBase64Encryption() ? new String(Base64.getDecoder().decode(dataTableInfo.getSql())) : dataTableInfo.getSql(); datasetSqlLog.setSql(sql); Datasource ds = datasourceMapper.selectByPrimaryKey(dataSetTableRequest.getDataSourceId()); if (ds == null) { throw DataManageException.getException(DEFINE_CN_DATASOURCE_INVALID); } String tmpSql = removeVariables(sql, ds.getType()); if (dataSetTableRequest.getMode() == 1 && (tmpSql.contains(SubstitutedParams) || tmpSql.contains(SubstitutedSql.trim()))) { throw DataManageException.getException("SQL变量只能用于直连"); } if (tmpSql.contains(SubstitutedParams)) { throw DataManageException.getException("SQL 变量只能在 WHERE 条件中使用"); } Provider datasourceProvider = ProviderFactory.getProvider(ds.getType()); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(ds); sql = handleVariableDefaultValue(sql, dataSetTableRequest.getSqlVariableDetails(), ds.getType()); if (StringUtils.isEmpty(sql)) { DataManageException.throwException("SQL 不能为空"); } checkVariable(sql, ds.getType()); QueryProvider qp = ProviderFactory.getQueryProvider(ds.getType()); String sqlAsTable = qp.createSQLPreview(sql, null); datasourceRequest.setQuery(sqlAsTable); Map<String, List> result; try { datasetSqlLog.setStartTime(System.currentTimeMillis()); result = datasourceProvider.fetchResultAndField(datasourceRequest); datasetSqlLog.setEndTime(System.currentTimeMillis()); datasetSqlLog.setSpend(datasetSqlLog.getEndTime() - datasetSqlLog.getStartTime()); datasetSqlLog.setStatus("Completed"); } catch (Exception e) { logger.error(e.getMessage()); datasetSqlLog.setStatus(DEFINE_ERROR); return ResultHolder.error(e.getMessage(), datasetSqlLog); } List<String[]> data = result.get("dataList"); List<TableField> fields = result.get("fieldList"); String[] fieldArray = fields.stream().map(TableField::getFieldName).toArray(String[]::new); if (checkIsRepeat(fieldArray)) { DataManageException.throwException("存在重复字段,请修改后重试"); } List<Map<String, Object>> jsonArray = new ArrayList<>(); if (CollectionUtils.isNotEmpty(data)) { jsonArray = data.stream().map(ele -> { Map<String, Object> map = new HashMap<>(); for (int i = 0; i < ele.length; i++) { map.put(fieldArray[i], ele[i]); } return map; }).collect(Collectors.toList()); } Map<String, Object> map = new HashMap<>(); map.put(DEFINE_FIELDS, fields); map.put("data", jsonArray); map.put("log", datasetSqlLog); return ResultHolder.success(map); } private String convertUnionTypeToSQL(String unionType) { switch (unionType) { case "1:1": case "inner": return " INNER JOIN "; case "1:N": case "left": return " LEFT JOIN "; case "N:1": case "right": return " RIGHT JOIN "; case "N:N": case "full": return " FULL JOIN "; default: return " INNER JOIN "; } } // 关联数据集从doris里预览数据 private Map<String, Object> getUnionSQLDoris(DataTableInfoDTO dataTableInfoDTO) { List<UnionDTO> union = dataTableInfoDTO.getUnion(); // 所有选中的字段,即select后的查询字段 Map<String, String[]> checkedInfo = new LinkedHashMap<>(); List<UnionParamDTO> unionList = new ArrayList<>(); List<DatasetTableField> checkedFields = new ArrayList<>(); String sql = ""; for (UnionDTO unionDTO : union) { // doris 使用数据集id做表名,拼sql将用到该名称 String tableId = unionDTO.getCurrentDs().getId(); String table = TableUtils.tableName(tableId); DatasetTable datasetTable = datasetTableMapper.selectByPrimaryKey(tableId); if (ObjectUtils.isEmpty(datasetTable)) { DEException.throwException(DEFINE_CN_DATASOURCE_DELETED + String.format(DEFINE_TABLE_ID, tableId)); } List<DatasetTableField> fields = dataSetTableFieldsService.getListByIdsEach(unionDTO.getCurrentDsField()); String[] array = fields.stream() .map(f -> table + "." + f.getDataeaseName() + " AS " + TableUtils.fieldName(tableId + "_" + f.getDataeaseName())) .toArray(String[]::new); checkedInfo.put(table, array); checkedFields.addAll(fields); // 获取child的fields和union if (CollectionUtils.isNotEmpty(unionDTO.getChildrenDs())) { getUnionSQLDorisJoin(unionDTO.getChildrenDs(), checkedInfo, unionList, checkedFields); } } // build sql if (CollectionUtils.isNotEmpty(unionList)) { // field StringBuilder field = new StringBuilder(); for (Map.Entry<String, String[]> next : checkedInfo.entrySet()) { field.append(StringUtils.join(next.getValue(), ",")).append(","); } String f = subPrefixSuffixChar(field.toString()); // join StringBuilder join = new StringBuilder(); for (UnionParamDTO unionParamDTO : unionList) { String joinType = convertUnionTypeToSQL(unionParamDTO.getUnionType()); UnionItemDTO u = unionParamDTO.getUnionFields().get(0); DatasetTableField pField = dataSetTableFieldsService.get(u.getParentField().getId()); DatasetTableField cField = dataSetTableFieldsService.get(u.getCurrentField().getId()); if (ObjectUtils.isEmpty(pField) || ObjectUtils.isEmpty(cField)) { DEException.throwException("该自定义数据集有关联字段被删除,请重新确认关联关系并重做该数据集"); } DatasetTable parentTable = datasetTableMapper.selectByPrimaryKey(pField.getTableId()); DatasetTable currentTable = datasetTableMapper.selectByPrimaryKey(cField.getTableId()); join.append(" ").append(joinType).append(" ").append(TableUtils.tableName(currentTable.getId())) .append(" ON "); for (int i = 0; i < unionParamDTO.getUnionFields().size(); i++) { UnionItemDTO unionItemDTO = unionParamDTO.getUnionFields().get(i); // 通过field id取得field详情,并且以第一组为准,寻找dataset table DatasetTableField parentField = dataSetTableFieldsService .get(unionItemDTO.getParentField().getId()); DatasetTableField currentField = dataSetTableFieldsService .get(unionItemDTO.getCurrentField().getId()); join.append(TableUtils.tableName(parentTable.getId())).append(".") .append(parentField.getDataeaseName()) .append(" = ") .append(TableUtils.tableName(currentTable.getId())).append(".") .append(currentField.getDataeaseName()); if (i < unionParamDTO.getUnionFields().size() - 1) { join.append(DEFINE_SPACE_AND_SPACE); } } } if (StringUtils.isEmpty(f)) { DEException.throwException(DEFINE_CN_DATASOURCE_NOT_FOUND_COLUMN); } sql = MessageFormat.format(DEFINE_SELECT_FROM, f, TableUtils.tableName(union.get(0).getCurrentDs().getId())) + join.toString(); } else { String f = StringUtils.join(checkedInfo.get(TableUtils.tableName(union.get(0).getCurrentDs().getId())), ","); if (StringUtils.isEmpty(f)) { throw DataManageException.getException(DEFINE_CN_DATASOURCE_NOT_FOUND_COLUMN); } sql = MessageFormat.format(DEFINE_SELECT_FROM, f, TableUtils.tableName(union.get(0).getCurrentDs().getId())); } Map<String, Object> map = new HashMap<>(); map.put("sql", sql); map.put(DEFINE_FIELD, checkedFields); map.put("join", unionList); return map; } // 递归计算出所有子级的checkedFields和unionParam private void getUnionSQLDorisJoin(List<UnionDTO> childrenDs, Map<String, String[]> checkedInfo, List<UnionParamDTO> unionList, List<DatasetTableField> checkedFields) { for (UnionDTO unionDTO : childrenDs) { String tableId = unionDTO.getCurrentDs().getId(); String table = TableUtils.tableName(tableId); DatasetTable datasetTable = datasetTableMapper.selectByPrimaryKey(tableId); if (ObjectUtils.isEmpty(datasetTable)) { DEException.throwException(DEFINE_CN_DATASOURCE_DELETED + String.format(DEFINE_TABLE_ID, tableId)); } List<DatasetTableField> fields = dataSetTableFieldsService.getListByIdsEach(unionDTO.getCurrentDsField()); String[] array = fields.stream() .map(f -> table + "." + f.getDataeaseName() + " AS " + TableUtils.fieldName(tableId + "_" + f.getDataeaseName())) .toArray(String[]::new); checkedInfo.put(table, array); checkedFields.addAll(fields); unionList.add(unionDTO.getUnionToParent()); if (CollectionUtils.isNotEmpty(unionDTO.getChildrenDs())) { getUnionSQLDorisJoin(unionDTO.getChildrenDs(), checkedInfo, unionList, checkedFields); } } } // 关联数据集 直连模式 public Map<String, Object> getUnionSQLDatasource(DataTableInfoDTO dataTableInfoDTO, Datasource ds) { DataSourceType dataSourceType = datasourceService.types().stream().filter(obj -> Objects.equals(obj.getType(), ds.getType())).collect(Collectors.toList()).get(0); String keyword = dataSourceType.getKeywordPrefix() + "%s" + dataSourceType.getKeywordSuffix(); String configuration = ds.getConfiguration(); JsonObject jsonObject = JsonParser.parseString(configuration).getAsJsonObject(); JsonElement schemaJson = jsonObject.get("schema"); String schema = null; if (schemaJson != null) { schema = schemaJson.getAsString(); } String joinPrefix = ""; if (StringUtils.isNotEmpty(schema) && (StringUtils.equalsIgnoreCase(ds.getType(), DatasourceTypes.db2.getType()) || StringUtils.equalsIgnoreCase(ds.getType(), DatasourceTypes.sqlServer.getType()) || StringUtils.equalsIgnoreCase(ds.getType(), DatasourceTypes.oracle.getType()) || StringUtils.equalsIgnoreCase(ds.getType(), DatasourceTypes.pg.getType()))) { joinPrefix = String.format(keyword, schema) + "."; } List<UnionDTO> union = dataTableInfoDTO.getUnion(); // 所有选中的字段,即select后的查询字段 Map<String, String[]> checkedInfo = new LinkedHashMap<>(); List<UnionParamDTO> unionList = new ArrayList<>(); List<DatasetTableField> checkedFields = new ArrayList<>(); String sql = ""; String tableName = new Gson() .fromJson(datasetTableMapper.selectByPrimaryKey(union.get(0).getCurrentDs().getId()).getInfo(), DataTableInfoDTO.class) .getTable(); for (UnionDTO unionDTO : union) { DatasetTable datasetTable = datasetTableMapper.selectByPrimaryKey(unionDTO.getCurrentDs().getId()); String table = new Gson().fromJson(datasetTable.getInfo(), DataTableInfoDTO.class).getTable(); String tableId = unionDTO.getCurrentDs().getId(); if (ObjectUtils.isEmpty(datasetTable)) { DEException.throwException(DEFINE_CN_DATASOURCE_DELETED + String.format(DEFINE_TABLE_ID, tableId)); } List<DatasetTableField> fields = dataSetTableFieldsService.getListByIdsEach(unionDTO.getCurrentDsField()); String[] array = fields.stream() .map(f -> String.format(keyword, table) + "." + String.format(keyword, f.getOriginName()) + " AS " + TableUtils.fieldNameShort(tableId + "_" + f.getOriginName())) .toArray(String[]::new); checkedInfo.put(table, array); checkedFields.addAll(fields); // 获取child的fields和union if (CollectionUtils.isNotEmpty(unionDTO.getChildrenDs())) { getUnionSQLDatasourceJoin(unionDTO.getChildrenDs(), checkedInfo, unionList, keyword, checkedFields); } } // build sql if (CollectionUtils.isNotEmpty(unionList)) { // field StringBuilder field = new StringBuilder(); for (Map.Entry<String, String[]> next : checkedInfo.entrySet()) { field.append(StringUtils.join(next.getValue(), ",")).append(","); } String f = subPrefixSuffixChar(field.toString()); // join StringBuilder join = new StringBuilder(); for (UnionParamDTO unionParamDTO : unionList) { String joinType = convertUnionTypeToSQL(unionParamDTO.getUnionType()); UnionItemDTO u = unionParamDTO.getUnionFields().get(0); DatasetTableField pField = dataSetTableFieldsService.get(u.getParentField().getId()); DatasetTableField cField = dataSetTableFieldsService.get(u.getCurrentField().getId()); if (ObjectUtils.isEmpty(pField) || ObjectUtils.isEmpty(cField)) { DEException.throwException(DEFINE_CN_DATASOURCE_DELETED); } DatasetTable parentTable = datasetTableMapper.selectByPrimaryKey(pField.getTableId()); String parentTableName = new Gson().fromJson(parentTable.getInfo(), DataTableInfoDTO.class).getTable(); DatasetTable currentTable = datasetTableMapper.selectByPrimaryKey(cField.getTableId()); String currentTableName = new Gson().fromJson(currentTable.getInfo(), DataTableInfoDTO.class) .getTable(); join.append(" ").append(joinType).append(" ").append(joinPrefix).append(String.format(keyword, currentTableName)) .append(" ON "); for (int i = 0; i < unionParamDTO.getUnionFields().size(); i++) { UnionItemDTO unionItemDTO = unionParamDTO.getUnionFields().get(i); // 通过field id取得field详情,并且以第一组为准,寻找dataset table DatasetTableField parentField = dataSetTableFieldsService .get(unionItemDTO.getParentField().getId()); DatasetTableField currentField = dataSetTableFieldsService .get(unionItemDTO.getCurrentField().getId()); join.append(String.format(keyword, parentTableName)).append(".") .append(String.format(keyword, parentField.getOriginName())) .append(" = ") .append(String.format(keyword, currentTableName)).append(".") .append(String.format(keyword, currentField.getOriginName())); if (i < unionParamDTO.getUnionFields().size() - 1) { join.append(DEFINE_SPACE_AND_SPACE); } } } if (StringUtils.isEmpty(f)) { DEException.throwException(DEFINE_CN_DATASOURCE_NOT_FOUND_COLUMN); } sql = MessageFormat.format(DEFINE_SELECT_FROM, f, joinPrefix + String.format(keyword, tableName)) + join.toString(); } else { String f = StringUtils.join(checkedInfo.get(tableName), ","); if (StringUtils.isEmpty(f)) { throw DataManageException.getException("前关联数据集,无选中字段,请重新编辑"); } sql = MessageFormat.format(DEFINE_SELECT_FROM, f, joinPrefix + String.format(keyword, tableName)); } Map<String, Object> map = new HashMap<>(); map.put("sql", sql); map.put(DEFINE_FIELD, checkedFields); map.put("join", unionList); return map; } private String subPrefixSuffixChar(String str) { while (StringUtils.startsWith(str, ",")) { str = str.substring(1, str.length()); } while (StringUtils.endsWith(str, ",")) { str = str.substring(0, str.length() - 1); } return str; } // 递归计算出所有子级的checkedFields和unionParam private void getUnionSQLDatasourceJoin(List<UnionDTO> childrenDs, Map<String, String[]> checkedInfo, List<UnionParamDTO> unionList, String keyword, List<DatasetTableField> checkedFields) { for (UnionDTO unionDTO : childrenDs) { DatasetTable datasetTable = datasetTableMapper.selectByPrimaryKey(unionDTO.getCurrentDs().getId()); String tableId = unionDTO.getCurrentDs().getId(); if (ObjectUtils.isEmpty(datasetTable)) { DEException.throwException(DEFINE_CN_DATASOURCE_DELETED + String.format(DEFINE_TABLE_ID, tableId)); } String table = new Gson().fromJson(datasetTable.getInfo(), DataTableInfoDTO.class).getTable(); List<DatasetTableField> fields = dataSetTableFieldsService.getListByIdsEach(unionDTO.getCurrentDsField()); String[] array = fields.stream() .map(f -> String.format(keyword, table) + "." + String.format(keyword, f.getOriginName()) + " AS " + TableUtils.fieldNameShort(tableId + "_" + f.getOriginName())) .toArray(String[]::new); checkedInfo.put(table, array); checkedFields.addAll(fields); unionList.add(unionDTO.getUnionToParent()); if (CollectionUtils.isNotEmpty(unionDTO.getChildrenDs())) { getUnionSQLDatasourceJoin(unionDTO.getChildrenDs(), checkedInfo, unionList, keyword, checkedFields); } } } public void saveTableField(DatasetTable datasetTable) throws DataManageException { Datasource ds = datasourceMapper.selectByPrimaryKey(datasetTable.getDataSourceId()); if (ObjectUtils.isEmpty(ds) && !datasetTable.getType().equalsIgnoreCase(DatasetType.UNION.name())) { throw DataManageException.getException(DEFINE_CN_DATA_DELETED); } DataSetTableRequest dataSetTableRequest = new DataSetTableRequest(); BeanUtils.copyBean(dataSetTableRequest, datasetTable); List<TableField> fields = new ArrayList<>(); long syncTime = System.currentTimeMillis(); if (StringUtils.equalsIgnoreCase(datasetTable.getType(), DatasetType.DB.name()) || StringUtils.equalsIgnoreCase(datasetTable.getType(), DatasetType.API.name())) { fields = getFields(datasetTable); } else if (StringUtils.equalsIgnoreCase(datasetTable.getType(), DatasetType.SQL.name())) { Provider datasourceProvider = ProviderFactory.getProvider(ds.getType()); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(ds); QueryProvider qp = ProviderFactory.getQueryProvider(ds.getType()); DataTableInfoDTO dataTableInfo = new Gson().fromJson(datasetTable.getInfo(), DataTableInfoDTO.class); String sql = dataTableInfo.isBase64Encryption() ? new String(Base64.getDecoder().decode(dataTableInfo.getSql())) : dataTableInfo.getSql(); sql = handleVariableDefaultValue(sql, null, ds.getType()); String sqlAsTable = qp.createSQLPreview(sql, null); datasourceRequest.setQuery(sqlAsTable); fields = datasourceProvider.fetchResultField(datasourceRequest); } else if (StringUtils.equalsIgnoreCase(datasetTable.getType(), DatasetType.EXCEL.name())) { fields = dataSetTableRequest.getFields(); } else if (StringUtils.equalsIgnoreCase(datasetTable.getType(), "union")) { if (datasetTable.getMode() == 1) { ds = engineService.getDeEngine(); Provider datasourceProvider = ProviderFactory.getProvider(ds.getType()); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(ds); // save field DataTableInfoDTO dataTableInfoDTO = new Gson().fromJson(dataSetTableRequest.getInfo(), DataTableInfoDTO.class); Map<String, Object> sqlMap = getUnionSQLDoris(dataTableInfoDTO); String sql = (String) sqlMap.get("sql"); List<DatasetTableField> fieldList = (List<DatasetTableField>) sqlMap.get(DEFINE_FIELD); // custom 创建doris视图 createDorisView(TableUtils.tableName(datasetTable.getId()), sql); datasourceRequest.setQuery(sql); fields = datasourceProvider.fetchResultField(datasourceRequest); for (DatasetTableField field : fieldList) { for (TableField tableField : fields) { if (StringUtils.equalsIgnoreCase( TableUtils.fieldName(field.getTableId() + "_" + field.getDataeaseName()), tableField.getFieldName())) { tableField.setRemarks(field.getName()); tableField.setFieldType(field.getType()); //将原有的type赋值给新创建的数据列 break; } } } } else { Provider datasourceProvider = ProviderFactory.getProvider(ds.getType()); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(ds); DataTableInfoDTO dt = new Gson().fromJson(datasetTable.getInfo(), DataTableInfoDTO.class); Map<String, Object> sqlMap = getUnionSQLDatasource(dt, ds); String sql = (String) sqlMap.get("sql"); List<DatasetTableField> fieldList = (List<DatasetTableField>) sqlMap.get(DEFINE_FIELD); datasourceRequest.setQuery(sql); fields = datasourceProvider.fetchResultField(datasourceRequest); for (DatasetTableField field : fieldList) { for (TableField tableField : fields) { if (StringUtils.equalsIgnoreCase( TableUtils.fieldNameShort(field.getTableId() + "_" + field.getOriginName()), tableField.getFieldName())) { tableField.setRemarks(field.getName()); break; } } } } } QueryProvider qp = null; if (!ObjectUtils.isEmpty(ds)) { qp = ProviderFactory.getQueryProvider(ds.getType()); } if (CollectionUtils.isNotEmpty(fields)) { List<String> originNameList = new ArrayList<>(); for (int i = 0; i < fields.size(); i++) { TableField field = fields.get(i); originNameList.add(field.getFieldName()); DatasetTableField datasetTableField = DatasetTableField.builder().build(); // 物理字段名设定为唯一,查询当前数据集下是否已存在该字段,存在则update,不存在则insert DatasetTableFieldExample datasetTableFieldExample = new DatasetTableFieldExample(); // 字段名一致,认为字段没有改变 datasetTableFieldExample.createCriteria().andTableIdEqualTo(datasetTable.getId()).andOriginNameEqualTo(field.getFieldName()); List<DatasetTableField> datasetTableFields = datasetTableFieldMapper.selectByExample(datasetTableFieldExample); if (CollectionUtils.isNotEmpty(datasetTableFields)) { datasetTableField.setId(datasetTableFields.get(0).getId()); datasetTableField.setOriginName(field.getFieldName()); datasetTableField.setType(field.getFieldType()); datasetTableField.setSize(field.getFieldSize()); datasetTableField.setAccuracy(field.getAccuracy()); if (ObjectUtils.isEmpty(ds)) { datasetTableField.setDeExtractType(transFieldType(field.getFieldType())); } else { Integer fieldType = qp.transFieldType(field.getFieldType()); datasetTableField.setDeExtractType(fieldType); } } else { datasetTableField.setTableId(datasetTable.getId()); datasetTableField.setOriginName(field.getFieldName()); datasetTableField.setName(field.getRemarks()); if (datasetTable.getMode() == 1 && StringUtils.equalsIgnoreCase("union", datasetTable.getType())) { datasetTableField.setDataeaseName(field.getFieldName()); } else { datasetTableField.setDataeaseName(TableUtils.columnName(field.getFieldName())); } datasetTableField.setType(field.getFieldType()); if (ObjectUtils.isEmpty(ds)) { datasetTableField.setDeType(transFieldType(field.getFieldType())); datasetTableField.setDeExtractType(transFieldType(field.getFieldType())); } else { Integer fieldType = qp.transFieldType(field.getFieldType()); Integer deType = 0; if(fieldType == 4){ deType = 2; } else { deType = fieldType == 6 ? 0 : fieldType; } datasetTableField.setDeType(deType); datasetTableField.setDeExtractType(fieldType); } datasetTableField.setSize(field.getFieldSize()); datasetTableField.setAccuracy(field.getAccuracy()); datasetTableField.setChecked(true); datasetTableField.setLastSyncTime(syncTime); datasetTableField.setExtField(0); datasetTableField.setGroupType((datasetTableField.getDeType() < 2 || datasetTableField.getDeType() == 6) ? "d" : "q"); } datasetTableField.setColumnIndex(i); dataSetTableFieldsService.save(datasetTableField); } // delete 数据库中多余的字段 DatasetTableFieldExample datasetTableFieldExample = new DatasetTableFieldExample(); datasetTableFieldExample.createCriteria().andTableIdEqualTo(datasetTable.getId()).andExtFieldEqualTo(0).andOriginNameNotIn(originNameList); datasetTableFieldMapper.deleteByExample(datasetTableFieldExample); } } private void createDorisView(String dorisTableName, String customSql) throws DataManageException { Datasource engine = engineService.getDeEngine(); JdbcProvider jdbcProvider = CommonBeanFactory.getBean(JdbcProvider.class); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(engine); DDLProvider ddlProvider = ProviderFactory.getDDLProvider(engine.getType()); // 先删除表 datasourceRequest.setQuery(ddlProvider.dropView(dorisTableName)); jdbcProvider.exec(datasourceRequest); datasourceRequest.setQuery(ddlProvider.createView(dorisTableName, customSql)); jdbcProvider.exec(datasourceRequest); } public Integer transFieldType(String field) { switch (field) { case "TEXT": return 0; case "DATETIME": return 1; case "LONG": case "INT": return 2; case "DOUBLE": return 3; default: return 0; } } private void checkNameAndCode(DatasetTable datasetTable) { DatasetTableExample datasetTableExample = new DatasetTableExample(); DatasetTableExample.Criteria criteria = datasetTableExample.createCriteria(); if (StringUtils.isNotEmpty(datasetTable.getId())) { criteria.andIdNotEqualTo(datasetTable.getId()); } if (StringUtils.isNotEmpty(datasetTable.getSceneId())) { criteria.andSceneIdEqualTo(datasetTable.getSceneId()); } if (StringUtils.isNotEmpty(datasetTable.getName())) { criteria.andNameEqualTo(datasetTable.getName()); } List<DatasetTable> list = datasetTableMapper.selectByExample(datasetTableExample); if (!list.isEmpty()) { throw DataManageException.getException(DEFINE_CN_NAME_USED); } //验证code if (null != datasetTable.getCode()) { DatasetTableExample tableExample = new DatasetTableExample(); DatasetTableExample.Criteria codeCriteria = tableExample.createCriteria(); if (StringUtils.isNotEmpty(datasetTable.getId())) { codeCriteria.andIdNotEqualTo(datasetTable.getId()); } if (StringUtils.isNotEmpty(datasetTable.getCode())) { codeCriteria.andCodeEqualTo(datasetTable.getCode()); } list = datasetTableMapper.selectByExample(tableExample); if (!list.isEmpty()) { throw DataManageException.getException("数据集编码已使用"); } } } private void checkNames(List<DataSetTableRequest> datasetTable) { if (CollectionUtils.isEmpty(datasetTable)) { return; } Set<String> nameSet = new HashSet<>(); for (DataSetTableRequest table : datasetTable) { nameSet.add(table.getName()); } if (nameSet.size() != datasetTable.size()) { throw DataManageException.getException(DEFINE_CN_NAME_USED); } DatasetTableExample datasetTableExample = new DatasetTableExample(); DatasetTableExample.Criteria criteria = datasetTableExample.createCriteria(); if (StringUtils.isNotEmpty(datasetTable.get(0).getSceneId())) { criteria.andSceneIdEqualTo(datasetTable.get(0).getSceneId()); } if (CollectionUtils.isNotEmpty(nameSet)) { criteria.andNameIn(new ArrayList<>(nameSet)); } List<DatasetTable> list = datasetTableMapper.selectByExample(datasetTableExample); if (!list.isEmpty()) { throw DataManageException.getException(DEFINE_CN_NAME_USED); } } public DataSetDetail getDatasetDetail(String id) { DataSetDetail dataSetDetail = new DataSetDetail(); DataSetTableDTO table = extDataSetTableMapper.findOneDetails(id); dataSetDetail.setTable(table); if (ObjectUtils.isNotEmpty(table)) { Datasource datasource = datasourceMapper.selectByPrimaryKey(table.getDataSourceId()); Optional.ofNullable(datasource).orElse(new Datasource()).setConfiguration(null); Collection<DataSourceType> types = datasourceService.types(); for (DataSourceType type : types) { if (ObjectUtils.isNotEmpty(datasource) && StringUtils.equalsIgnoreCase(datasource.getType(), type.getType())) { datasource.setType(type.getName()); break; } } dataSetDetail.setDatasource(datasource); } return dataSetDetail; } public Boolean checkEngineTableIsExists(String id) throws DataManageException { Datasource engine = engineService.getDeEngine(); JdbcProvider jdbcProvider = CommonBeanFactory.getBean(JdbcProvider.class); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(engine); QueryProvider qp = ProviderFactory.getQueryProvider(engine.getType()); datasourceRequest.setQuery(qp.searchTable(TableUtils.tableName(id))); List<String[]> data = jdbcProvider.getData(datasourceRequest); return CollectionUtils.isNotEmpty(data); } /* * 判断数组中是否有重复的值 */ public static boolean checkIsRepeat(String[] array) { HashSet<String> hashSet = new HashSet<>(); for (String s : array) { if (StringUtils.isEmpty(s)) { throw DataManageException.getException("第一行存在空单元格"); } hashSet.add(s); } return hashSet.size() != array.length; } public DatasetTable syncDatasetTableField(String id) throws DataManageException { DatasetTable datasetTable = datasetTableMapper.selectByPrimaryKey(id); saveTableField(datasetTable); return datasetTable; } public int updateByExampleSelective(DatasetTable record, DatasetTableExample example) { return datasetTableMapper.updateByExampleSelective(record, example); } private ExpressionDeParser getExpressionDeParser(StringBuilder stringBuilder) { ExpressionDeParser expressionDeParser = new ExpressionDeParser(null, stringBuilder) { @Override public void visit(Parenthesis parenthesis) { getBuffer().append("("); parenthesis.getExpression().accept(this); getBuffer().append(")"); } @Override public void visit(OrExpression orExpression) { visitBinaryExpr(orExpression, "OR"); } @Override public void visit(AndExpression andExpression) { visitBinaryExpr(andExpression, "AND"); } @Override public void visit(Between between) { if (hasVariable(between.getBetweenExpressionStart().toString()) || hasVariable(between.getBetweenExpressionEnd().toString())) { getBuffer().append(SubstitutedSql); } else { getBuffer().append(between.getLeftExpression()).append(" BETWEEN ").append(between.getBetweenExpressionStart()).append(DEFINE_SPACE_AND_SPACE).append(between.getBetweenExpressionEnd()); } } @Override public void visit(MinorThan minorThan) { if (hasVariable(minorThan.getLeftExpression().toString()) || hasVariable(minorThan.getRightExpression().toString())) { getBuffer().append(SubstitutedSql); return; } getBuffer().append(minorThan.getLeftExpression()); getBuffer().append(" < "); getBuffer().append(minorThan.getRightExpression()); } @Override public void visit(MinorThanEquals minorThan) { if (hasVariable(minorThan.getLeftExpression().toString()) || hasVariable(minorThan.getRightExpression().toString())) { getBuffer().append(SubstitutedSql); return; } getBuffer().append(minorThan.getLeftExpression()); getBuffer().append(" <= "); getBuffer().append(minorThan.getRightExpression()); } @Override public void visit(GreaterThanEquals minorThan) { if (hasVariable(minorThan.getLeftExpression().toString()) || hasVariable(minorThan.getRightExpression().toString())) { getBuffer().append(SubstitutedSql); return; } getBuffer().append(minorThan.getLeftExpression()); getBuffer().append(" >= "); getBuffer().append(minorThan.getRightExpression()); } @Override public void visit(GreaterThan greaterThan) { if (hasVariable(greaterThan.getLeftExpression().toString()) || hasVariable(greaterThan.getRightExpression().toString())) { getBuffer().append(SubstitutedSql); return; } getBuffer().append(greaterThan.getLeftExpression()); getBuffer().append(" > "); getBuffer().append(greaterThan.getRightExpression()); } @Override public void visit(ExpressionList expressionList) { for (Iterator<Expression> iter = expressionList.getExpressions().iterator(); iter.hasNext(); ) { Expression expression = iter.next(); expression.accept(this); if (iter.hasNext()) { buffer.append(", "); } } } @Override public void visit(LikeExpression likeExpression) { if (hasVariable(likeExpression.toString())) { getBuffer().append(SubstitutedSql); return; } visitBinaryExpression(likeExpression, (likeExpression.isNot() ? " NOT" : "") + (likeExpression.isCaseInsensitive() ? " ILIKE " : " LIKE ")); String escape = likeExpression.getEscape(); if (escape != null) { buffer.append(" ESCAPE '").append(escape).append('\''); } } @Override public void visit(InExpression inExpression) { if (inExpression.getRightItemsList() != null && hasVariable(inExpression.getRightItemsList().toString())) { stringBuilder.append(SubstitutedSql); return; } if (inExpression.getRightExpression() != null && inExpression.getRightExpression().toString().equals(SubstitutedParams)) { stringBuilder.append(SubstitutedSql); return; } inExpression.getLeftExpression().accept(this); if (inExpression.isNot()) { getBuffer().append(" " + " NOT IN " + " "); } else { getBuffer().append(" IN "); } if (inExpression.getRightItemsList() != null) { getBuffer().append(inExpression.getRightItemsList()); } if (inExpression.getRightExpression() != null) { getBuffer().append(" ( "); inExpression.getRightExpression().accept(this); getBuffer().append(" )"); } } @Override public void visit(SubSelect subSelect) { StringBuilder stringBuilder = new StringBuilder(); Expression in = ((PlainSelect) subSelect.getSelectBody()).getWhere(); if (in instanceof BinaryExpression && hasVariable(in.toString())) { stringBuilder.append(SubstitutedParams); } else { in.accept(getExpressionDeParser(stringBuilder)); } try { Expression where = CCJSqlParserUtil.parseCondExpression(stringBuilder.toString()); ((PlainSelect) subSelect.getSelectBody()).setWhere(where); getBuffer().append(subSelect.getSelectBody()); } catch (Exception e) { logger.error(e.getMessage()); } } private void visitBinaryExpr(BinaryExpression expr, String operator) { boolean hasSubBinaryExpression = false; try { BinaryExpression leftBinaryExpression = (BinaryExpression) expr.getLeftExpression(); hasSubBinaryExpression = leftBinaryExpression instanceof AndExpression || leftBinaryExpression instanceof OrExpression; } catch (Exception e) { logger.error(e.getMessage()); } if (expr.getLeftExpression() instanceof BinaryExpression && !hasSubBinaryExpression && hasVariable(expr.getLeftExpression().toString())) { getBuffer().append(SubstitutedSql); } else { expr.getLeftExpression().accept(this); } getBuffer().append(" " + operator + " "); hasSubBinaryExpression = false; try { BinaryExpression rightBinaryExpression = (BinaryExpression) expr.getRightExpression(); hasSubBinaryExpression = rightBinaryExpression instanceof AndExpression || rightBinaryExpression instanceof OrExpression; ; } catch (Exception e) { logger.error(e.getMessage()); } if (expr.getRightExpression() instanceof BinaryExpression && !hasSubBinaryExpression && hasVariable(expr.getRightExpression().toString())) { getBuffer().append(SubstitutedSql); } else { expr.getRightExpression().accept(this); } } }; return expressionDeParser; } private static boolean hasVariable(String sql) { return sql.contains(SubstitutedParams); } public void exportDataset(DataSetExportRequest request, HttpServletResponse response) throws DataManageException { try (Workbook wb = new XSSFWorkbook()) { DatasetRowPermissionsTreeObj tree = null; Datasource datasource = datasourceService.get(request.getDataSourceId()); int pageSize = (datasource != null && StringUtils.equalsIgnoreCase(datasource.getType(), "es")) ? 10000 : 100000; request.setRow(String.valueOf(pageSize)); Map<String, Object> previewData = getPreviewData(request, 1, pageSize, null, tree); List<DatasetTableField> fields = (List<DatasetTableField>) previewData.get(DEFINE_FIELDS); List<Map<String, Object>> data = (List<Map<String, Object>>) previewData.get("data"); // 构建Excel数据格式 List<List<String>> details = new ArrayList<>(); List<String> header = new ArrayList<>(); for (DatasetTableField field : fields) { header.add(field.getName()); } details.add(header); for (Map<String, Object> obj : data) { List<String> row = new ArrayList<>(); for (DatasetTableField field : fields) { String string = (String) obj.get(field.getDataeaseName()); row.add(string); } details.add(row); } // 操作Excel //Workbook wb = new XSSFWorkbook(); // Sheet Sheet detailsSheet = wb.createSheet("数据"); //给单元格设置样式 CellStyle cellStyle = wb.createCellStyle(); Font font = wb.createFont(); //设置字体大小 font.setFontHeightInPoints((short) 12); //设置字体加粗 font.setBold(true); //给字体设置样式 cellStyle.setFont(font); //设置单元格背景颜色 cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); //设置单元格填充样式(使用纯色背景颜色填充) cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); if (CollectionUtils.isNotEmpty(details)) { for (int i = 0; i < details.size(); i++) { Row row = detailsSheet.createRow(i); List<String> rowData = details.get(i); if (rowData != null) { for (int j = 0; j < rowData.size(); j++) { Cell cell = row.createCell(j); if (i == 0) {// 头部 cell.setCellValue(rowData.get(j)); cell.setCellStyle(cellStyle); //设置列的宽度 detailsSheet.setColumnWidth(j, 255 * 20); } else { if ((fields.get(j).getDeType().equals(DeTypeConstants.DE_INT) || fields.get(j).getDeType().equals(DeTypeConstants.DE_FLOAT)) && StringUtils.isNotEmpty(rowData.get(j))) { cell.setCellValue(Double.valueOf(rowData.get(j))); } else { cell.setCellValue(rowData.get(j)); } } } } } } OutputStream outputStream = response.getOutputStream(); response.setContentType("application/vnd.ms-excel"); //文件名称 response.setHeader("Content-disposition", "attachment;filename=" + request.getFilename() + ".xlsx"); wb.write(outputStream); outputStream.flush(); outputStream.close(); } catch (Exception e) { logger.error(e.getMessage()); DataManageException.throwException(e); } } /** * @param datasourceCode * @return */ public List<Map> getDatasetsFromDatasource(String datasourceCode) { List<Map> tables = new ArrayList<>(); DatasourceExample example = new DatasourceExample(); DatasourceExample.Criteria criteria = example.createCriteria(); criteria.andCodeEqualTo(datasourceCode); //根据code查询数据源信息 List<Datasource> datasourceList = datasourceMapper.selectByExample(example); if (CollectionUtils.isEmpty(datasourceList)) { return tables; } Datasource datasource = datasourceList.get(0); //拿到数据源下的数据集 DatasetTableExample datasetTableExample = new DatasetTableExample(); datasetTableExample.createCriteria().andDataSourceIdEqualTo(datasource.getId()); List<DatasetTable> datasetTables = datasetTableMapper.selectByExample(datasetTableExample); if (CollectionUtils.isEmpty(datasetTables)) { return tables; } List<String> dataTableIds = datasetTables.stream().map(DatasetTable::getId).collect(Collectors.toList()); List<DatasetTableField> tableFieldList = dataSetTableFieldsService.getFieldsByTableIds(dataTableIds); Map<String, List<DatasetTableField>> tableFieldMap = tableFieldList.stream().collect(Collectors.groupingBy(DatasetTableField::getTableId)); datasetTables.forEach(table -> { Map map = new HashMap(); map.put("datasetTtableId", table.getId()); map.put("datasetTtableName", table.getName()); map.put("datasetTtableCode", table.getCode()); map.put("datasetTtableType", table.getType()); map.put("datasetTtableInfo", table.getInfo()); map.put("datasourceCode", datasourceCode); map.put("datasourceId", datasource.getId()); List<TableFieldDTO> fieldDTOs = new ArrayList<>(); List<DatasetTableField> tableFields = tableFieldMap.get(table.getId()); tableFields.forEach(tableField -> { TableFieldDTO dto = new TableFieldDTO(); dto.setColumnType(tableField.getType()); dto.setColumnComments(tableField.getName()); String originName = tableField.getOriginName(); if (tableField.getExtField() == 2) { //数据源管理手动新增的字段前后会有'',需要去掉。 if (originName.startsWith("'")) { originName = originName.replaceFirst("'", ""); } if (originName.endsWith("'")) { originName = originName.replaceFirst("(?s)" + "'" + "(?!.*?" + "'" + ")", ""); } } dto.setColumnName(originName); fieldDTOs.add(dto); }); map.put("tableFields", fieldDTOs); tables.add(map); }); return tables; }}
package cn.chinatowercom.dataflow.datasource.service;import cn.chinatowercom.dataflow.datasource.exception.DEException;import cn.chinatowercom.dataflow.datasource.provider.datasource.ApiProvider;import cn.chinatowercom.dataflow.datasource.service.abstractservice.AbstractDatasourceService;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.google.gson.Gson;import com.google.gson.JsonObject;import com.google.gson.JsonParser;import com.google.gson.reflect.TypeToken;import com.strongdata.dataflow.core.datasource.commons.config.JdbcConfiguration;import com.strongdata.dataflow.core.datasource.commons.config.MysqlConfiguration;import com.strongdata.dataflow.core.datasource.commons.config.OracleConfiguration;import com.strongdata.dataflow.core.datasource.commons.config.ProviderFactory;import com.strongdata.dataflow.core.datasource.commons.constants.DatasetType;import com.strongdata.dataflow.core.datasource.commons.constants.DatasourceCalculationMode;import com.strongdata.dataflow.core.datasource.commons.constants.DatasourceTypes;import com.strongdata.dataflow.core.datasource.commons.constants.RedisConstants;import com.strongdata.dataflow.core.datasource.entity.*;import com.strongdata.dataflow.core.datasource.entity.dto.*;import com.strongdata.dataflow.core.datasource.entity.request.DatasourceRequest;import com.strongdata.dataflow.core.datasource.entity.request.DatasourceUnionRequest;import com.strongdata.dataflow.core.datasource.exception.DataManageException;import com.strongdata.dataflow.core.datasource.mapper.DatasetTableMapper;import com.strongdata.dataflow.core.datasource.mapper.DatasourceMapper;import com.strongdata.dataflow.core.datasource.mapper.ExtDataSourceMapper;import com.strongdata.dataflow.core.datasource.provider.Provider;import com.strongdata.dataflow.core.datasource.utils.BeanUtils;import com.strongdata.dataflow.core.datasource.utils.CommonThreadPool;import com.strongdata.dataflow.core.datasource.utils.LogUtil;import com.strongdata.dataflow.core.datasource.utils.SpringContextUtil;import lombok.extern.slf4j.Slf4j;import org.apache.commons.collections4.CollectionUtils;import org.apache.commons.lang3.ObjectUtils;import org.apache.commons.lang3.StringUtils;import org.springframework.core.env.Environment;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import javax.annotation.Resource;import java.time.LocalDateTime;import java.util.*;import java.util.stream.Collectors;@Service@Slf4jpublic class DatasourceService { private final static String DEFINE_SUCCESS = "Success"; private final static String DEFINE_ERROR = "Error"; @Resource private DatasourceMapper datasourceMapper; @Resource private ExtDataSourceMapper extDataSourceMapper; @Resource private DatasetTableMapper datasetTableMapper; @Resource private DataSetGroupService dataSetGroupService; @Resource private CommonThreadPool commonThreadPool; @Resource private Environment env; @Resource private SystemParameterService systemParameterService; @Resource private DriverService driverService; @Resource private SysProjectDatasourceService sysProjectDatasourceService; public Collection<DataSourceType> types() { Collection<DataSourceType> types = new ArrayList<>(); types.addAll(SpringContextUtil.getApplicationContext().getBeansOfType(DataSourceType.class).values()); SpringContextUtil.getApplicationContext().getBeansOfType(AbstractDatasourceService.class).values().forEach(abstractDatasourceService -> { types.add(abstractDatasourceService.getDataSourceType()); }); List<String> dataList = new ArrayList<>(Arrays.asList("mysql","mariadb","oracle")); Collection<DataSourceType> newtypes = types.stream().filter(dataSourceType -> dataList.contains(dataSourceType.getType())).collect(Collectors.toList()); return newtypes; } //@DeCleaner(DePermissionType.DATASOURCE) @Transactional(rollbackFor = Exception.class) public Datasource addDatasource(DatasourceDTO datasource) throws DataManageException { preCheckDs(datasource); return insert(datasource); } // @DeCleaner(DePermissionType.DATASOURCE) public DatasourceDTO insert(DatasourceDTO datasource) { long currentTimeMillis = System.currentTimeMillis(); datasource.setId(UUID.randomUUID().toString()); datasource.setUpdateTime(currentTimeMillis); datasource.setCreateTime(currentTimeMillis); // : 2023/2/17 当前用户 datasource.setCreateBy("1"); checkAndUpdateDatasourceStatus(datasource); datasourceMapper.insertSelective(datasource); handleConnectionPool(datasource, "add"); // : 2023/2/17 权限 //保存数据源和项目的对应关系 SysProjectDatasource sysProjectDatasource = new SysProjectDatasource(); sysProjectDatasource.setDatasourceId(datasource.getId()); sysProjectDatasource.setProjectId(datasource.getProjectId()); sysProjectDatasource.setCreateTime(LocalDateTime.now()); sysProjectDatasource.setCreateBy(datasource.getCreateBy()); sysProjectDatasourceService.saveProjectDatasource(sysProjectDatasource); return datasource; } public void preCheckDs(DatasourceDTO datasource) throws DataManageException { if (!types().stream().map(DataSourceType::getType).collect(Collectors.toList()).contains(datasource.getType())) { throw DataManageException.getException("Datasource type not supported."); } if (datasource.isConfigurationEncryption()) { datasource.setConfiguration(new String(Base64.getDecoder().decode(datasource.getConfiguration()))); } Provider datasourceProvider = ProviderFactory.getProvider(datasource.getType()); datasourceProvider.checkConfiguration(datasource); checkNameAndCode(datasource.getName(), datasource.getCode(), datasource.getType(), datasource.getId()); //如果是API类型数据源,验证数据源接口code if (datasource.getType().equalsIgnoreCase(DatasourceTypes.api.toString())) { checkDatasourceTableCode(datasource.getConfiguration(), datasource.getId()); } } public void handleConnectionPool(String datasourceId, String type) { Datasource datasource = datasourceMapper.selectByPrimaryKey(datasourceId); if (datasource == null) { return; } handleConnectionPool(datasource, type); } public void handleConnectionPool(Datasource datasource, String type) { commonThreadPool.addTask(() -> { try { Provider datasourceProvider = ProviderFactory.getProvider(datasource.getType()); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(datasource); datasourceProvider.handleDatasource(datasourceRequest, type); LogUtil.info("Success to {} datasource connection pool: {}", type, datasource.getName()); } catch (Exception e) { LogUtil.error("Failed to handle datasource connection pool: " + datasource.getName(), e); } }); } public List<DatasourceDTO> getDatasourceList(DatasourceUnionRequest request) throws DataManageException { List<DatasourceDTO> datasourceDTOS = extDataSourceMapper.queryUnion(request); datasourceDTOS.forEach(this::datasourceTrans); if (StringUtils.isBlank(request.getSort())) { datasourceDTOS.sort((o1, o2) -> { int tmp = StringUtils.compareIgnoreCase(o1.getTypeDesc(), o2.getTypeDesc()); if (tmp == 0) { tmp = StringUtils.compareIgnoreCase(o1.getName(), o2.getName()); } return tmp; }); } return datasourceDTOS; } /** * 查询RDP页面数据源信息 * * @param request * @return * @throws DataManageException */ public List<DatasourceRdpDTO> getRdpDatasourceList(DatasourceUnionRequest request) throws DataManageException { List<DatasourceDTO> datasourceDTOS = extDataSourceMapper.queryUnion(request); List<DatasourceRdpDTO> datasourceList = new ArrayList<>(); datasourceDTOS.forEach(datasourceDTO -> { DatasourceRdpDTO ds = new DatasourceRdpDTO(); BeanUtils.copyBean(ds, datasourceDTO); ds.setDatasourceCode(datasourceDTO.getCode()); ds.setDataSourceName(datasourceDTO.getName()); datasourceList.add(ds); }); return datasourceList; } private void datasourceTrans(DatasourceDTO datasourceDTO) { types().forEach(dataSourceType -> { if (dataSourceType.getType().equalsIgnoreCase(datasourceDTO.getType())) { datasourceDTO.setTypeDesc(dataSourceType.getName()); datasourceDTO.setCalculationMode(dataSourceType.getCalculationMode()); } }); if (!datasourceDTO.getType().equalsIgnoreCase(DatasourceTypes.api.toString())) { JdbcConfiguration configuration = new Gson().fromJson(datasourceDTO.getConfiguration(), JdbcConfiguration.class); if (StringUtils.isNotEmpty(configuration.getCustomDriver()) && !configuration.getCustomDriver().equalsIgnoreCase("default")) { datasourceDTO.setCalculationMode(DatasourceCalculationMode.DIRECT); } JSONObject jsonObject = JSON.parseObject(datasourceDTO.getConfiguration()); if (jsonObject.getString("queryTimeout") == null) { jsonObject.put("queryTimeout", 30); datasourceDTO.setConfiguration(jsonObject.toString()); } } if (datasourceDTO.getType().equalsIgnoreCase(DatasourceTypes.mysql.toString())) { MysqlConfiguration mysqlConfiguration = new Gson().fromJson(datasourceDTO.getConfiguration(), MysqlConfiguration.class); datasourceDTO.setConfiguration(new Gson().toJson(mysqlConfiguration)); } if (datasourceDTO.getType().equalsIgnoreCase(DatasourceTypes.api.toString())) { List<ApiDefinition> apiDefinitionList = new Gson().fromJson(datasourceDTO.getConfiguration(), new TypeToken<ArrayList<ApiDefinition>>() { }.getType()); List<ApiDefinition> apiDefinitionListWithStatus = new ArrayList<>(); int success = 0; if (StringUtils.isNotEmpty(datasourceDTO.getStatus())) { JsonObject apiItemStatuses = JsonParser.parseString(datasourceDTO.getStatus()).getAsJsonObject(); for (int i = 0; i < apiDefinitionList.size(); i++) { String status = null; if (apiItemStatuses.get(apiDefinitionList.get(i).getName()) != null) { status = apiItemStatuses.get(apiDefinitionList.get(i).getName()).getAsString(); } apiDefinitionList.get(i).setStatus(status); apiDefinitionList.get(i).setSerialNumber(i); apiDefinitionListWithStatus.add(apiDefinitionList.get(i)); if (StringUtils.isNotEmpty(status) && status.equalsIgnoreCase(DEFINE_SUCCESS)) { success++; } } } datasourceDTO.setApiConfiguration(apiDefinitionListWithStatus); if (success == apiDefinitionList.size()) { datasourceDTO.setStatus(DEFINE_SUCCESS); } else { if (success > 0 && success < apiDefinitionList.size()) { datasourceDTO.setStatus("Warning"); } else { datasourceDTO.setStatus(DEFINE_ERROR); } } } if (StringUtils.isNotEmpty(datasourceDTO.getConfiguration())) { datasourceDTO.setConfiguration(new String(Base64.getEncoder().encode(datasourceDTO.getConfiguration().getBytes()))); } if (CollectionUtils.isNotEmpty(datasourceDTO.getApiConfiguration())) { String config = new Gson().toJson(datasourceDTO.getApiConfiguration()); datasourceDTO.setApiConfigurationStr(new String(Base64.getEncoder().encode(config.getBytes()))); datasourceDTO.setApiConfiguration(null); } } public DatasourceDTO getDataSourceDetails(String datasourceId) { // : 2023/2/17 获取当前用户 DatasourceDTO result = extDataSourceMapper.queryDetails(datasourceId, "1"); if (result != null) { this.datasourceTrans(result); } return result; } //@DeCleaner(DePermissionType.DATASOURCE) public ResultHolder deleteDatasource(String datasourceId) throws DataManageException { DatasetTableExample example = new DatasetTableExample(); example.createCriteria().andDataSourceIdEqualTo(datasourceId); List<DatasetTable> datasetTables = datasetTableMapper.selectByExample(example); if (CollectionUtils.isNotEmpty(datasetTables)) { return ResultHolder.error(datasetTables.size() + "个数据集正在使用此数据源,无法删除"); } Datasource datasource = datasourceMapper.selectByPrimaryKey(datasourceId); datasourceMapper.deleteByPrimaryKey(datasourceId); handleConnectionPool(datasource, "delete"); return ResultHolder.success(DEFINE_SUCCESS); } public void updateDatasource(String id, Datasource datasource, String projectId) { DatasourceExample example = new DatasourceExample(); example.createCriteria().andIdEqualTo(id); checkAndUpdateDatasourceStatus(datasource); datasourceMapper.updateByExampleSelective(datasource, example); //先删除原有的对应关系再保存数据源和项目的对应关系 SysProjectDatasource sysProjectDatasource = new SysProjectDatasource(); sysProjectDatasource.setDatasourceId(datasource.getId()); sysProjectDatasourceService.delProjectDatasource(sysProjectDatasource); sysProjectDatasource.setProjectId(projectId); sysProjectDatasource.setCreateTime(LocalDateTime.now()); sysProjectDatasource.setCreateBy(datasource.getCreateBy()); sysProjectDatasourceService.saveProjectDatasource(sysProjectDatasource); handleConnectionPool(id); if (datasource.getType().equalsIgnoreCase("api")) { DatasetTableExample datasetTableExample = new DatasetTableExample(); datasetTableExample.createCriteria().andDataSourceIdEqualTo(id); List<DatasetTable> datasetTables = datasetTableMapper.selectByExample(datasetTableExample); List<ApiDefinition> apiDefinitionList = new Gson().fromJson(datasource.getConfiguration(), new TypeToken<List<ApiDefinition>>() { }.getType()); apiDefinitionList.forEach(apiDefinition -> { if (apiDefinition.isReName()) { datasetTables.forEach(datasetTable -> { log.debug(new Gson().fromJson(datasetTable.getInfo(), DataTableInfoDTO.class).getTable()); log.debug(apiDefinition.getOrgName()); if (new Gson().fromJson(datasetTable.getInfo(), DataTableInfoDTO.class).getTable().equals(apiDefinition.getOrgName())) { DatasetTable record = new DatasetTable(); DataTableInfoDTO dataTableInfoDTO = new DataTableInfoDTO(); dataTableInfoDTO.setTable(apiDefinition.getName()); record.setInfo(new Gson().toJson(dataTableInfoDTO)); datasetTableExample.clear(); datasetTableExample.createCriteria().andIdEqualTo(datasetTable.getId()); datasetTableMapper.updateByExampleSelective(record, datasetTableExample); } }); } }); } } private void handleConnectionPool(String datasourceId) { String cacheType = env.getProperty("spring.cache.type"); if (cacheType != null && cacheType.equalsIgnoreCase("redis")) { handleConnectionPool(datasourceId, "delete"); RedisTemplate redisTemplate = SpringContextUtil.getBean("redisTemplate", RedisTemplate.class); redisTemplate.convertAndSend(RedisConstants.DS_REDIS_TOPIC, datasourceId); } else { handleConnectionPool(datasourceId, "edit"); } } public ResultHolder validate(DatasourceDTO datasource) throws DataManageException { if (datasource.isConfigurationEncryption()) { datasource.setConfiguration(new String(Base64.getDecoder().decode(datasource.getConfiguration()))); } DatasourceDTO datasourceDTO = new DatasourceDTO(); BeanUtils.copyBean(datasourceDTO, datasource); try { Provider datasourceProvider = ProviderFactory.getProvider(datasource.getType()); datasourceProvider.checkConfiguration(datasource); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(datasource); String datasourceStatus = datasourceProvider.checkStatus(datasourceRequest); if (datasource.getType().equalsIgnoreCase("api")) { int success = 0; List<ApiDefinition> apiDefinitionList = new Gson().fromJson(datasource.getConfiguration(), new TypeToken<List<ApiDefinition>>() { }.getType()); List<ApiDefinition> apiDefinitionListWithStatus = new ArrayList<>(); if (StringUtils.isNotEmpty(datasourceStatus)) { JsonObject apiItemStatuses = JsonParser.parseString(datasourceStatus).getAsJsonObject(); for (ApiDefinition apiDefinition : apiDefinitionList) { String status = apiItemStatuses.get(apiDefinition.getName()).getAsString(); apiDefinition.setStatus(status); apiDefinitionListWithStatus.add(apiDefinition); if (StringUtils.isNotEmpty(status) && status.equalsIgnoreCase(DEFINE_SUCCESS)) { success++; } } } datasourceDTO.setApiConfiguration(apiDefinitionListWithStatus); if (success == apiDefinitionList.size()) { datasource.setStatus(datasourceStatus); return ResultHolder.success(datasourceDTO); } if (success > 0 && success < apiDefinitionList.size()) { return ResultHolder.error("数据源中有无效的表", datasourceDTO); } return ResultHolder.error("数据源无效", datasourceDTO); } return ResultHolder.success(datasourceDTO); } catch (Exception e) { return ResultHolder.error("数据源无效: " + e.getMessage()); } } public ResultHolder validate(String datasourceId) { Datasource datasource = datasourceMapper.selectByPrimaryKey(datasourceId); if (datasource == null) { return ResultHolder.error("Can not find datasource: " + datasourceId); } String datasourceStatus = null; try { Provider datasourceProvider = ProviderFactory.getProvider(datasource.getType()); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(datasource); datasourceStatus = datasourceProvider.checkStatus(datasourceRequest); if (datasource.getType().equalsIgnoreCase("api")) { List<ApiDefinition> apiDefinitionList = new Gson().fromJson(datasource.getConfiguration(), new TypeToken<List<ApiDefinition>>() { }.getType()); JsonObject apiItemStatuses = JsonParser.parseString(datasourceStatus).getAsJsonObject(); int success = 0; for (ApiDefinition apiDefinition : apiDefinitionList) { String status = apiItemStatuses.get(apiDefinition.getName()).getAsString(); apiDefinition.setStatus(status); if (status.equalsIgnoreCase(DEFINE_SUCCESS)) { success++; } } if (success == apiDefinitionList.size()) { datasource.setStatus(datasourceStatus); return ResultHolder.success(datasource); } if (success > 0 && success < apiDefinitionList.size()) { return ResultHolder.error("数据源中有无效的表", datasource); } return ResultHolder.error("数据源无效", datasource); } return ResultHolder.success(DEFINE_SUCCESS); } catch (Exception e) { datasourceStatus = DEFINE_ERROR; return ResultHolder.error("数据源无效: " + e.getMessage()); } finally { Datasource record = new Datasource(); record.setStatus(datasourceStatus); DatasourceExample example = new DatasourceExample(); example.createCriteria().andIdEqualTo(datasource.getId()); datasourceMapper.updateByExampleSelective(record, example); } } public List<String> getSchema(DatasourceDTO datasource) throws DataManageException { if (datasource.isConfigurationEncryption()) { datasource.setConfiguration(new String(Base64.getDecoder().decode(datasource.getConfiguration()))); } Provider datasourceProvider = ProviderFactory.getProvider(datasource.getType()); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(datasource); return datasourceProvider.getSchema(datasourceRequest); } /** * 查询数据源下属所有表 * * @param id * @return * @throws DataManageException */ public List<DBTableDTO> getTables(String id) throws DataManageException { Datasource ds = datasourceMapper.selectByPrimaryKey(id); Provider datasourceProvider = ProviderFactory.getProvider(ds.getType()); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(ds); if (!ds.getType().equalsIgnoreCase(DatasetType.API.name())) { datasourceProvider.checkStatus(datasourceRequest); } List<TableDesc> tables = datasourceProvider.getTables(datasourceRequest); // 获取当前数据源下的db、api类型数据集 DatasetTableExample datasetTableExample = new DatasetTableExample(); datasetTableExample.createCriteria().andTypeIn(Arrays.asList(DatasetType.DB.name(), DatasetType.API.name())).andDataSourceIdEqualTo(ds.getId()); List<DatasetTable> datasetTables = datasetTableMapper.selectByExample(datasetTableExample); List<DBTableDTO> list = new ArrayList<>(); for (TableDesc tableDesc : tables) { DBTableDTO dbTableDTO = new DBTableDTO(); dbTableDTO.setDatasourceId(ds.getId()); dbTableDTO.setDatasourceCode(ds.getCode()); dbTableDTO.setName(tableDesc.getName()); dbTableDTO.setRemark(tableDesc.getRemark()); dbTableDTO.setTableCode(tableDesc.getTableCode()); dbTableDTO.setEnableCheck(true); dbTableDTO.setDatasetPath(null); for (DatasetTable datasetTable : datasetTables) { DataTableInfoDTO dataTableInfoDTO = new Gson().fromJson(datasetTable.getInfo(), DataTableInfoDTO.class); if (StringUtils.equals(tableDesc.getName(), dataTableInfoDTO.getTable())) { dbTableDTO.setEnableCheck(false); List<DatasetGroup> parents = dataSetGroupService.getParents(datasetTable.getSceneId()); StringBuilder stringBuilder = new StringBuilder(); parents.forEach(ele -> { if (ObjectUtils.isNotEmpty(ele)) { stringBuilder.append(ele.getName()).append("/"); } }); stringBuilder.append(datasetTable.getName()); dbTableDTO.setDatasetPath(stringBuilder.toString()); break; } } list.add(dbTableDTO); } return list; } public Datasource get(String id) { return datasourceMapper.selectByPrimaryKey(id); } public List<Datasource> selectByType(String type) { DatasourceExample datasourceExample = new DatasourceExample(); datasourceExample.createCriteria().andTypeEqualTo(type); return datasourceMapper.selectByExampleWithBLOBs(datasourceExample); } public void initAllDataSourceConnectionPool() { List<Datasource> datasources = datasourceMapper.selectByExampleWithBLOBs(new DatasourceExample()); datasources.forEach(datasource -> { commonThreadPool.addTask(() -> { try { handleConnectionPool(datasource, "add"); } catch (Exception e) { LogUtil.error("Failed to init datasource: " + datasource.getName(), e); } }); }); } public void checkNameAndCode(String datasourceName, String datasourceCode, String type, String id) { DatasourceExample example = new DatasourceExample(); DatasourceExample.Criteria criteria = example.createCriteria(); criteria.andNameEqualTo(datasourceName); criteria.andTypeEqualTo(type); if (StringUtils.isNotEmpty(id)) { criteria.andIdNotEqualTo(id); } if (CollectionUtils.isNotEmpty(datasourceMapper.selectByExample(example))) { DEException.throwException("数据源名称已被使用"); } //验证code if (null != datasourceCode) { DatasourceExample datasourceExample = new DatasourceExample(); DatasourceExample.Criteria codeCriteria = datasourceExample.createCriteria(); if (StringUtils.isNotEmpty(id)) { codeCriteria.andIdNotEqualTo(id); } codeCriteria.andCodeEqualTo(datasourceCode); if (CollectionUtils.isNotEmpty(datasourceMapper.selectByExample(datasourceExample))) { DEException.throwException("数据源编码已被使用"); } } } /** * 验证数据源接口code * * @param configuration * @param id */ public void checkDatasourceTableCode(String configuration, String id) { List<ApiDefinition> apiDefinitionList = new Gson().fromJson(configuration, new TypeToken<ArrayList<ApiDefinition>>() { }.getType()); List<String> apiCodeList = apiDefinitionList.stream().map(apiDefinition -> apiDefinition.getTableCode()).collect(Collectors.toList()); HashSet<String> apiCodeSet = new HashSet<>(apiCodeList); if (apiCodeList.size() != apiCodeSet.size()) { DEException.throwException("数据表编码不能重复"); } DatasetTableExample datasetTableExample = new DatasetTableExample(); DatasetTableExample.Criteria criteria = datasetTableExample.createCriteria(); criteria.andCodeIn(apiCodeList); if (StringUtils.isNotEmpty(id)) { criteria.andDataSourceIdNotEqualTo(id); } List<DatasetTable> datasetTables = datasetTableMapper.selectByExample(datasetTableExample); if (!datasetTables.isEmpty()) { List<String> tableCode = datasetTables.stream().map(table -> table.getCode()).collect(Collectors.toList()); String code = StringUtils.join(tableCode, ","); DEException.throwException("数据表编码:" + code + "已被使用"); } } public ApiDefinition checkApiDatasource(ApiDefinition apiDefinition) throws DataManageException { BasicInfo basicInfo = systemParameterService.basicInfo(); String response = ApiProvider.execHttpRequest(apiDefinition, StringUtils.isNotBlank(basicInfo.getFrontTimeOut()) ? Integer.parseInt(basicInfo.getFrontTimeOut()) : 10); return ApiProvider.checkApiDefinition(apiDefinition, response); } public List<Datasource> listByType(String type) { DatasourceExample example = new DatasourceExample(); example.createCriteria().andTypeEqualTo(type); return datasourceMapper.selectByExampleWithBLOBs(example); } public void checkAndUpdateDatasourceStatus(Datasource datasource) { try { Provider datasourceProvider = ProviderFactory.getProvider(datasource.getType()); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(datasource); String status = datasourceProvider.checkStatus(datasourceRequest); datasource.setStatus(status); } catch (Exception e) { datasource.setStatus(DEFINE_ERROR); } }// private void checkAndUpdateDatasourceStatus(Datasource datasource, Boolean withMsg) {// Datasource record = new Datasource();// DatasourceExample example = new DatasourceExample();// example.createCriteria().andIdEqualTo(datasource.getId());// try {// Provider datasourceProvider = ProviderFactory.getProvider(datasource.getType());// DatasourceRequest datasourceRequest = new DatasourceRequest();// datasourceRequest.setDatasource(datasource);// String status = datasourceProvider.checkStatus(datasourceRequest);// record.setStatus(status);// datasourceMapper.updateByExampleSelective(record, example);// } catch (Exception e) {// Datasource temp = datasourceMapper.selectByPrimaryKey(datasource.getId());// record.setStatus(DEFINE_ERROR);// if (!StringUtils.equals(temp.getStatus(), DEFINE_ERROR)) {// //sendWebMsg(datasource);// datasourceMapper.updateByExampleSelective(record, example);// }// }// } /** * 查询数据集对应的数据源信息 * * @param dataSetCode * @return */ public ResultHolder getDatasetsFromDatasource(String dataSetCode) { DatasetTableExample datasetTableExample = new DatasetTableExample(); datasetTableExample.createCriteria().andCodeEqualTo(dataSetCode); List<DatasetTable> datasetTables = datasetTableMapper.selectByExample(datasetTableExample); if (CollectionUtils.isEmpty(datasetTables)) { return ResultHolder.error("数据集不存在或已删除"); } //根据数据集拿到数据源的id,进行数据源信息查询 DatasetTable datasetTable = datasetTables.get(0); String dataSourceId = datasetTable.getDataSourceId(); String info = datasetTable.getInfo(); String tableName = new Gson().fromJson(info, DataTableInfoDTO.class).getTable(); Datasource datasource = datasourceMapper.selectByPrimaryKey(dataSourceId); if (datasource == null) { return ResultHolder.error("数据源不存在或已删除"); } //连接信息 DatasourceConnDTO datasourceConnDTO = new DatasourceConnDTO(); datasourceConnDTO.setDatasourceId(datasource.getId()); datasourceConnDTO.setDatasourceName(datasource.getName()); datasourceConnDTO.setDatasourceCode(datasource.getCode()); datasourceConnDTO.setDatasourceType(datasource.getType()); datasourceConnDTO.setDatasetId(datasetTable.getId()); datasourceConnDTO.setDatasetName(datasetTable.getName()); datasourceConnDTO.setDatasetCode(datasetTable.getCode()); datasourceConnDTO.setDatasetTableName(tableName); if (datasource.getType().equalsIgnoreCase("api")) { List<ApiDefinition> apiDefinitionList = new Gson().fromJson(datasource.getConfiguration(), new TypeToken<List<ApiDefinition>>() { }.getType()); if (CollectionUtils.isEmpty(apiDefinitionList)) { return ResultHolder.error("数据源中没有配置数据表"); } for (ApiDefinition apiDefinition : apiDefinitionList) { String name = apiDefinition.getName(); if (name.equals(tableName)) { DatasourceApiConnDTO datasourceApiConnDTO = new DatasourceApiConnDTO(); BeanUtils.copyBean(datasourceApiConnDTO, apiDefinition); datasourceConnDTO.setDatasourceApiConnDTO(datasourceApiConnDTO); break; } } } else { DatasourceJdbcConnDTO datasourceJdbcConnDTO = new DatasourceJdbcConnDTO(); if (datasource.getType().equalsIgnoreCase("mysql") || datasource.getType().equalsIgnoreCase("mariadb")) { MysqlConfiguration mysqlConfiguration = new Gson().fromJson(datasource.getConfiguration(), MysqlConfiguration.class); BeanUtils.copyBean(datasourceJdbcConnDTO, mysqlConfiguration); datasourceJdbcConnDTO.setUrl(mysqlConfiguration.getJdbc()); datasourceJdbcConnDTO.setDriverClass(mysqlConfiguration.getDriver()); } else if (datasource.getType().equalsIgnoreCase("oracle")) { OracleConfiguration oracleConfiguration = new Gson().fromJson(datasource.getConfiguration(), OracleConfiguration.class); BeanUtils.copyBean(datasourceJdbcConnDTO, oracleConfiguration); datasourceJdbcConnDTO.setUrl(oracleConfiguration.getJdbc()); datasourceJdbcConnDTO.setDriverClass(oracleConfiguration.getDriver()); } //如果使用的不是默认驱动 if (!isDefaultClassLoader(datasourceJdbcConnDTO.getCustomDriver())) { DeDriver deDriver = driverService.selectByPrimaryKey(datasourceJdbcConnDTO.getCustomDriver()); datasourceJdbcConnDTO.setDriverClass(deDriver.getDriverClass()); } datasourceJdbcConnDTO.setDataSourceType(datasource.getType()); datasourceConnDTO.setDatasourceJdbcConnDTO(datasourceJdbcConnDTO); } return ResultHolder.success(datasourceConnDTO); } protected boolean isDefaultClassLoader(String customDriver) { return StringUtils.isEmpty(customDriver) || customDriver.equalsIgnoreCase("default"); }}
package cn.chinatowercom.dataflow.datasource.service;import cn.hutool.core.bean.BeanUtil;import cn.hutool.core.collection.CollUtil;import com.google.gson.Gson;import com.strongdata.dataflow.core.datasource.commons.config.JdbcConfiguration;import com.strongdata.dataflow.core.datasource.commons.config.ProviderFactory;import com.strongdata.dataflow.core.datasource.entity.*;import com.strongdata.dataflow.core.datasource.entity.dto.DriverDTO;import com.strongdata.dataflow.core.datasource.exception.DataManageException;import com.strongdata.dataflow.core.datasource.mapper.DeDriverDetailsMapper;import com.strongdata.dataflow.core.datasource.mapper.DeDriverMapper;import com.strongdata.dataflow.core.datasource.provider.DefaultJdbcProvider;import com.strongdata.dataflow.core.datasource.provider.ExtendedJdbcClassLoader;import com.strongdata.dataflow.core.datasource.utils.BeanUtils;import com.strongdata.dataflow.core.datasource.utils.DeFileUtils;import com.strongdata.dataflow.core.datasource.utils.LogUtil;import com.strongdata.dataflow.core.datasource.utils.Md5Utils;import lombok.SneakyThrows;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;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.io.FileInputStream;import java.io.FileOutputStream;import java.io.OutputStream;import java.lang.reflect.Modifier;import java.net.MalformedURLException;import java.nio.charset.StandardCharsets;import java.util.ArrayList;import java.util.List;import java.util.UUID;@Transactional(rollbackFor = Exception.class)@Service@Slf4jpublic class DriverService { private static final String NOT_FOUND_DRIVER = "未找到驱动"; @Value("${file.root.dir}") private String rootPath; private static String DRIVER_PATH = "/custom-drivers/"; @Resource private DeDriverMapper deDriverMapper; @Resource private DeDriverDetailsMapper deDriverDetailsMapper; @Resource private DatasourceService datasourceService; public List<DriverDTO> list() throws DataManageException { List<DriverDTO> driverDTOS = new ArrayList<>(); deDriverMapper.selectByExample(null).forEach(deDriver -> { DriverDTO driverDTO = new DriverDTO(); BeanUtils.copyBean(driverDTO, deDriver); datasourceService.types().forEach(dataSourceType -> { if (dataSourceType.getType().equalsIgnoreCase(deDriver.getType())) { driverDTO.setTypeDesc(dataSourceType.getName()); } }); driverDTOS.add(driverDTO); }); return driverDTOS; } public void delete(DeDriver deDriver) { for (Datasource datasource : datasourceService.listByType(deDriver.getType())) { JdbcConfiguration configuration = new Gson().fromJson(datasource.getConfiguration(), JdbcConfiguration.class); if (StringUtils.isNotEmpty(configuration.getCustomDriver()) && configuration.getCustomDriver().equalsIgnoreCase(deDriver.getId())) { DataManageException.throwException("使用中的驱动不允许删除"); } } deDriverMapper.deleteByPrimaryKey(deDriver.getId()); DeDriverDetailsExample example = new DeDriverDetailsExample(); example.createCriteria().andDeDriverIdEqualTo(deDriver.getId()); deDriverDetailsMapper.deleteByExample(example); DeFileUtils.deleteFile(rootPath + DRIVER_PATH + deDriver.getId() + "/"); } public DeDriver save(DeDriver deDriver) { if (StringUtils.isEmpty(deDriver.getName()) || StringUtils.isEmpty(deDriver.getType())) { DataManageException.throwException("Name or Type cannot be empty."); } DeDriverExample example = new DeDriverExample(); example.createCriteria().andNameEqualTo(deDriver.getName()); if (CollUtil.isNotEmpty(deDriverMapper.selectByExample(example))) { DataManageException.throwException("名称重复"); } deDriver.setCreateTime(System.currentTimeMillis()); deDriver.setId(UUID.randomUUID().toString()); deDriverMapper.insert(deDriver); return deDriver; } public DeDriver update(DeDriver deDriver) { deDriverMapper.updateByPrimaryKey(deDriver); return deDriver; } public List<DeDriverDetails> listDriverDetails(String driverId) { DeDriverDetailsExample example = new DeDriverDetailsExample(); example.createCriteria().andDeDriverIdEqualTo(driverId); return deDriverDetailsMapper.selectByExample(example); } public void deleteDriverFile(String driverFileId) throws DataManageException, MalformedURLException { DeDriverDetails deDriverDetails = deDriverDetailsMapper.selectByPrimaryKey(driverFileId); DeDriver deDriver = deDriverMapper.selectByPrimaryKey(deDriverDetails.getDeDriverId()); if (deDriver == null) { DataManageException.throwException(NOT_FOUND_DRIVER); return; } if (deDriverDetails.getIsTransName() == null || !deDriverDetails.getIsTransName()) { DeFileUtils.deleteFile(rootPath + DRIVER_PATH + deDriverDetails.getDeDriverId() + "/" + deDriverDetails.getFileName()); } else { DeFileUtils.deleteFile(rootPath + DRIVER_PATH + deDriverDetails.getDeDriverId() + "/" + deDriverDetails.getTransName()); } deDriverDetailsMapper.deleteByPrimaryKey(driverFileId); if(BeanUtil.isNotEmpty(deDriver)) { DefaultJdbcProvider defaultJdbcProvider = (DefaultJdbcProvider) ProviderFactory.getProvider(deDriver.getType()); defaultJdbcProvider.reloadCustomJdbcClassLoader(deDriver); } } public DeDriverDetails saveJar(MultipartFile file, String driverId) throws DataManageException, MalformedURLException { DeDriver deDriver = deDriverMapper.selectByPrimaryKey(driverId); if (deDriver == null) { DataManageException.throwException(NOT_FOUND_DRIVER); return null; } if (file == null || file.isEmpty()) { DataManageException.throwException("文件不能为空"); return null; } String filename = file.getOriginalFilename(); if (null != filename && !filename.endsWith(".jar")) { DataManageException.throwException("文件不是 jar 包!"); } String dirPath = rootPath + DRIVER_PATH + driverId + "/"; String filePath = dirPath + Md5Utils.md5(filename) + ".jar"; saveFile(file, dirPath, filePath); List<String> jdbcList = new ArrayList<>(); String version = ""; DeDriverDetails deDriverDetails = new DeDriverDetails(); deDriverDetails.setId(UUID.randomUUID().toString()); deDriverDetails.setDeDriverId(driverId); deDriverDetails.setVersion(version); deDriverDetails.setFileName(filename); deDriverDetails.setDriverClass(String.join(",", jdbcList)); deDriverDetails.setIsTransName(true); deDriverDetails.setTransName(Md5Utils.md5(filename) + ".jar"); deDriverDetails.setFilePath(filePath); DeDriverDetailsExample deDriverDetailsExample = new DeDriverDetailsExample(); deDriverDetailsExample.createCriteria().andDeDriverIdEqualTo(driverId).andFileNameEqualTo(filename); if (CollUtil.isNotEmpty(deDriverDetailsMapper.selectByExample(deDriverDetailsExample))) { DataManageException.throwException("A file with the same name already exists:" + filename); } deDriverDetailsMapper.insert(deDriverDetails); DefaultJdbcProvider defaultJdbcProvider = (DefaultJdbcProvider) ProviderFactory.getProvider(deDriver.getType()); defaultJdbcProvider.reloadCustomJdbcClassLoader(deDriver); return deDriverDetails; } /** * 下载文件 * * @param driverFileId * @param request * @param response * @return */ @SneakyThrows public void driverFileDown(String driverFileId, HttpServletRequest request, HttpServletResponse response) { //查询导入导出文件信息 DeDriverDetails deDriverDetails = deDriverDetailsMapper.selectByPrimaryKey(driverFileId); DeDriver deDriver = deDriverMapper.selectByPrimaryKey(deDriverDetails.getDeDriverId()); if (deDriver == null) { DataManageException.throwException(NOT_FOUND_DRIVER); } String filePath = deDriverDetails.getFilePath(); String originalName = deDriverDetails.getFileName(); //下载文件 downFile(filePath, originalName, request, response); }// private List<String> getClassNameFrom(String jarName) {// List<String> fileList = new ArrayList<String>();// try (JarFile jarFile = new JarFile(new File(jarName))) {// Enumeration<JarEntry> en = jarFile.entries(); // 枚举获得JAR文件内的实体,即相对路径// while (en.hasMoreElements()) {// String name1 = en.nextElement().getName();// if (!name1.endsWith(".class")) {//不是class文件// continue;// }// String name2 = name1.substring(0, name1.lastIndexOf(".class"));// String name3 = name2.replaceAll("/", ".");// fileList.add(name3);// }// } catch (IOException e) {// e.printStackTrace();// }// return fileList;// } public boolean isChildClass(String className, Class parentClazz, ExtendedJdbcClassLoader extendedJdbcClassLoader) { if (className == null) return false; Class clazz = null; try { clazz = extendedJdbcClassLoader.loadClass(className); if (Modifier.isAbstract(clazz.getModifiers())) {//抽象类忽略 return false; } if (Modifier.isInterface(clazz.getModifiers())) {//接口忽略 return false; } } catch (Exception e) { LogUtil.error(e); return false; } return parentClazz.isAssignableFrom(clazz); }// private String classVersion(ExtendedJdbcClassLoader extendedJdbcClassLoader, String className) throws DataManageException {// Class clazz = extendedJdbcClassLoader.loadClass(className);// return clazz.getPackage().getImplementationVersion();// } private String saveFile(MultipartFile file, String dirPath, String filePath) { File p = new File(dirPath); if (!p.exists()) { p.mkdirs(); } File f = null; try { f = new File(filePath); } catch (Exception e) { DataManageException.throwException("保存文件失败"); return null; } try (FileOutputStream fileOutputStream = new FileOutputStream(f)){ fileOutputStream.write(file.getBytes()); return filePath; } catch (Exception e) { DataManageException.throwException("保存文件失败"); } return filePath; } @SneakyThrows private void downFile(String filePath, String originalName, HttpServletRequest request, HttpServletResponse response) { OutputStream out = null; FileInputStream input = null; try { File file = new File(filePath); if (!file.exists()) { DataManageException.throwException("文件未找到"); } if (StringUtils.isBlank(originalName)) { originalName = filePath.substring(filePath.lastIndexOf(File.separator)); } if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > -1) { originalName = new String(originalName.getBytes("GB2312"), StandardCharsets.ISO_8859_1); } else { originalName = java.net.URLEncoder.encode(originalName, "UTF-8"); originalName = new String(originalName.getBytes(StandardCharsets.UTF_8), "GBK"); } response.setContentType("application/octet-stream;charset=utf-8"); response.setHeader("Content-disposition", "attachment;filename=" + originalName); out = response.getOutputStream(); input = new FileInputStream(file); byte[] charbuffer = new byte[1024]; int length = 0; while ((length = input.read(charbuffer)) != -1) { out.write(charbuffer, 0, length); } } finally { if (null != input) { try { input.close(); } catch (Exception e) { log.error("关闭文件输入流失败", e); } } if (null != out) { try { out.flush(); out.close(); } catch (Exception e) { log.error("关闭文件输出流失败", e); } } } } public DeDriver selectByPrimaryKey(String customDriver) { return deDriverMapper.selectByPrimaryKey(customDriver); }}
package cn.chinatowercom.dataflow.datasource.service;import com.google.gson.Gson;import com.google.gson.JsonArray;import com.google.gson.JsonObject;import com.google.gson.JsonParser;import com.strongdata.dataflow.core.datasource.commons.config.DorisConfiguration;import com.strongdata.dataflow.core.datasource.commons.config.MysqlConfiguration;import com.strongdata.dataflow.core.datasource.commons.config.ProviderFactory;import com.strongdata.dataflow.core.datasource.entity.*;import com.strongdata.dataflow.core.datasource.entity.request.DatasourceRequest;import com.strongdata.dataflow.core.datasource.exception.DataManageException;import com.strongdata.dataflow.core.datasource.mapper.DeEngineMapper;import com.strongdata.dataflow.core.datasource.provider.Provider;import com.strongdata.dataflow.core.datasource.utils.BeanUtils;import com.strongdata.dataflow.core.datasource.utils.HttpClientUtil;import lombok.extern.slf4j.Slf4j;import org.apache.commons.collections4.CollectionUtils;import org.apache.commons.lang3.StringUtils;import org.springframework.core.env.Environment;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import javax.annotation.Resource;import java.util.*;import java.util.regex.Matcher;import java.util.regex.Pattern;@Service@Transactional(rollbackFor = Exception.class)@Slf4jpublic class EngineService { private final static String DEFINE_ENGINE_MYSQL = "engine_mysql"; private final static String DEFINE_ENGINE_DORIS = "engine_doris"; private final static String DEFINE_ENGINE_MODE = "engine_mode"; private final static String DEFINE_LOCAL = "local"; private final static String DEFINE_DORIS = "doris"; @Resource private Environment env; @Resource private DeEngineMapper deEngineMapper; @Resource private DatasourceService datasource; static private List<String> simple_engine = Arrays.asList(DEFINE_ENGINE_MYSQL); static private List<String> cluster_engine = Arrays.asList(DEFINE_ENGINE_DORIS); public Boolean isLocalMode() { return env.getProperty(DEFINE_ENGINE_MODE, DEFINE_LOCAL).equalsIgnoreCase(DEFINE_LOCAL); } public Boolean isSimpleMode() { return env.getProperty(DEFINE_ENGINE_MODE, DEFINE_LOCAL).equalsIgnoreCase("simple"); } public Boolean isClusterMode() { return env.getProperty(DEFINE_ENGINE_MODE, DEFINE_LOCAL).equalsIgnoreCase("cluster"); } public String mode() { return env.getProperty(DEFINE_ENGINE_MODE, DEFINE_LOCAL); } public DeEngine info() { DeEngineExample deEngineExample = new DeEngineExample(); if (isClusterMode()) { deEngineExample.createCriteria().andTypeEqualTo(DEFINE_ENGINE_DORIS); } else { deEngineExample.createCriteria().andTypeEqualTo(DEFINE_ENGINE_MYSQL); } List<DeEngine> deEngines = deEngineMapper.selectByExampleWithBLOBs(deEngineExample); if (CollectionUtils.isEmpty(deEngines)) { return new DeEngine(); } return deEngines.get(0); } public ResultHolder validate(Datasource datasource) throws DataManageException { if (StringUtils.isEmpty(datasource.getType()) || StringUtils.isEmpty(datasource.getConfiguration())) { throw DataManageException.getException("未完整设置数据引擎"); } try { Provider datasourceProvider = ProviderFactory.getProvider(datasource.getType()); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(datasource); datasourceProvider.checkStatus(datasourceRequest); } catch (Exception e) { return ResultHolder.error("Engine is invalid: " + e.getMessage()); } if (datasource.getType().equalsIgnoreCase(DEFINE_ENGINE_DORIS)) { DorisConfiguration dorisConfiguration = new Gson().fromJson(datasource.getConfiguration(), DorisConfiguration.class); HttpClientConfig httpClientConfig = new HttpClientConfig(); String authValue = "Basic " + Base64.getUrlEncoder().encodeToString((dorisConfiguration.getUsername() + ":" + dorisConfiguration.getPassword()).getBytes()); httpClientConfig.addHeader("Authorization", authValue); String response; try { response = HttpClientUtil.get("http://" + dorisConfiguration.getHost() + ":" + dorisConfiguration.getHttpPort() + "/api/backends", httpClientConfig); } catch (Exception e) { return ResultHolder.error("Engine is invalid: " + e.getMessage()); } JsonArray backends = null; JsonObject data = JsonParser.parseString(response).getAsJsonObject().getAsJsonObject("data"); if (data != null) { backends = data.getAsJsonArray("backends"); } if (backends == null || backends.size() == 0) { return ResultHolder.error("Engine is invalid: no backends found."); } Integer alives = 0; for (int i = 0; i < backends.size(); i++) { JsonObject kv = backends.get(i).getAsJsonObject(); if (kv.get("is_alive").getAsBoolean()) { alives++; } } if (alives < dorisConfiguration.getReplicationNum()) { return ResultHolder.error("Engine params is invalid: 副本数量不能大于节点数量."); } } return ResultHolder.success(datasource); } public ResultHolder save(DeEngine engine) throws DataManageException { checkValid(engine); if (StringUtils.isEmpty(engine.getId())) { engine.setId(UUID.randomUUID().toString()); deEngineMapper.insert(engine); } else { deEngineMapper.updateByPrimaryKeyWithBLOBs(engine); datasource.handleConnectionPool(getDeEngine(), "delete"); } setDs(engine); datasource.handleConnectionPool(getDeEngine(), "add"); return ResultHolder.success(engine); } private void checkValid(DeEngine engine) throws DataManageException { if (isLocalMode()) { throw DataManageException.getException("Setting engine is not supported."); } if (isSimpleMode() && !simple_engine.contains(engine.getType())) { throw DataManageException.getException("Engine type not supported."); } if (isClusterMode() && !cluster_engine.contains(engine.getType())) { throw DataManageException.getException("Engine type not supported."); } } private void setDs(DeEngine engine) { // : 2023/2/17 清除缓存 //CacheUtils.removeAll("ENGINE"); log.debug(engine.toString()); } // @Cacheable(value = "ENGINE") public Datasource getDeEngine() throws DataManageException { Datasource datasource1 = new Datasource(); if (isLocalMode()) { Map jsonObjectMap = new HashMap(); jsonObjectMap.put("dataSourceType", "jdbc"); jsonObjectMap.put("dataBase", env.getProperty("doris.db", DEFINE_DORIS)); jsonObjectMap.put("username", env.getProperty("doris.user", "root")); jsonObjectMap.put("password", env.getProperty("doris.password", "dataease")); jsonObjectMap.put("host", env.getProperty("doris.host", DEFINE_DORIS)); jsonObjectMap.put("port", env.getProperty("doris.port", "9030")); jsonObjectMap.put("httpPort", env.getProperty("doris.httpPort", "8030")); DeEngine engine = new DeEngine(); engine.setId(DEFINE_DORIS); engine.setName(DEFINE_DORIS); engine.setDesc(DEFINE_DORIS); engine.setType(DEFINE_ENGINE_DORIS); engine.setConfiguration(new Gson().toJson(jsonObjectMap)); BeanUtils.copyBean(datasource1, engine); } if (isClusterMode()) { DeEngineExample engineExample = new DeEngineExample(); engineExample.createCriteria().andTypeEqualTo(DEFINE_ENGINE_DORIS); List<DeEngine> deEngines = deEngineMapper.selectByExampleWithBLOBs(engineExample); if (CollectionUtils.isEmpty(deEngines)) { throw DataManageException.getException("未设置数据引擎"); } BeanUtils.copyBean(datasource1, deEngines.get(0)); } if (isSimpleMode()) { DeEngineExample engineExample = new DeEngineExample(); engineExample.createCriteria().andTypeEqualTo(DEFINE_ENGINE_MYSQL); List<DeEngine> deEngines = deEngineMapper.selectByExampleWithBLOBs(engineExample); if (CollectionUtils.isEmpty(deEngines)) { throw DataManageException.getException("未设置数据引擎"); } BeanUtils.copyBean(datasource1, deEngines.get(0)); } return datasource1; } public void initSimpleEngine() { if (!isSimpleMode()) { return; } DeEngineExample engineExample = new DeEngineExample(); engineExample.createCriteria().andTypeEqualTo(DEFINE_ENGINE_MYSQL); List<DeEngine> deEngines = deEngineMapper.selectByExampleWithBLOBs(engineExample); if (CollectionUtils.isNotEmpty(deEngines)) { return; } DeEngine engine = new DeEngine(); engine.setId(UUID.randomUUID().toString()); engine.setType(DEFINE_ENGINE_MYSQL); MysqlConfiguration mysqlConfiguration = new MysqlConfiguration(); Pattern WITH_SQL_FRAGMENT = Pattern.compile("jdbc:mysql://(.*):(\\d+)/(.*)"); Matcher matcher = WITH_SQL_FRAGMENT.matcher(env.getProperty("spring.datasource.url")); if (!matcher.find()) { return; } ; mysqlConfiguration.setHost(matcher.group(1)); mysqlConfiguration.setPort(Integer.valueOf(matcher.group(2))); mysqlConfiguration.setDataBase(matcher.group(3).split("\\?")[0]); mysqlConfiguration.setExtraParams(matcher.group(3).split("\\?")[1]); mysqlConfiguration.setUsername(env.getProperty("spring.datasource.username")); mysqlConfiguration.setPassword(env.getProperty("spring.datasource.password")); engine.setConfiguration(new Gson().toJson(mysqlConfiguration)); deEngineMapper.insert(engine); }}
package cn.chinatowercom.dataflow.datasource.service;import cn.chinatowercom.dataflow.datasource.provider.datasource.JdbcProvider;import com.google.gson.Gson;import com.google.gson.reflect.TypeToken;import com.strongdata.dataflow.core.datasource.commons.config.*;import com.strongdata.dataflow.core.datasource.commons.constants.*;import com.strongdata.dataflow.core.datasource.entity.*;import com.strongdata.dataflow.core.datasource.entity.dto.DataTableInfoDTO;import com.strongdata.dataflow.core.datasource.entity.request.DatasourceRequest;import com.strongdata.dataflow.core.datasource.exception.DataManageException;import com.strongdata.dataflow.core.datasource.provider.DDLProvider;import com.strongdata.dataflow.core.datasource.provider.Provider;import com.strongdata.dataflow.core.datasource.provider.query.QueryProvider;import com.strongdata.dataflow.core.datasource.utils.CommonBeanFactory;import com.strongdata.dataflow.core.datasource.utils.LogUtil;import com.strongdata.dataflow.core.datasource.utils.Md5Utils;import com.strongdata.dataflow.core.datasource.utils.TableUtils;import lombok.SneakyThrows;import lombok.extern.slf4j.Slf4j;import org.apache.commons.collections4.CollectionUtils;import org.apache.commons.io.FileUtils;import org.apache.commons.lang3.StringUtils;import org.pentaho.di.cluster.SlaveServer;import org.pentaho.di.core.database.DatabaseMeta;import org.pentaho.di.core.exception.KettleException;import org.pentaho.di.core.row.ValueMetaInterface;import org.pentaho.di.core.row.value.ValueMetaBase;import org.pentaho.di.job.Job;import org.pentaho.di.job.JobExecutionConfiguration;import org.pentaho.di.job.JobHopMeta;import org.pentaho.di.job.JobMeta;import org.pentaho.di.job.entries.shell.JobEntryShell;import org.pentaho.di.job.entries.special.JobEntrySpecial;import org.pentaho.di.job.entries.success.JobEntrySuccess;import org.pentaho.di.job.entry.JobEntryCopy;import org.pentaho.di.repository.RepositoryDirectoryInterface;import org.pentaho.di.repository.filerep.KettleFileRepository;import org.pentaho.di.trans.Trans;import org.pentaho.di.trans.TransExecutionConfiguration;import org.pentaho.di.trans.TransHopMeta;import org.pentaho.di.trans.TransMeta;import org.pentaho.di.trans.step.StepMeta;import org.pentaho.di.trans.steps.csvinput.CsvInputMeta;import org.pentaho.di.trans.steps.excelinput.ExcelInputField;import org.pentaho.di.trans.steps.excelinput.ExcelInputMeta;import org.pentaho.di.trans.steps.excelinput.SpreadSheetType;import org.pentaho.di.trans.steps.tableinput.TableInputMeta;import org.pentaho.di.trans.steps.textfileinput.TextFileInputField;import org.pentaho.di.trans.steps.textfileoutput.TextFileField;import org.pentaho.di.trans.steps.textfileoutput.TextFileOutputMeta;import org.pentaho.di.trans.steps.userdefinedjavaclass.UserDefinedJavaClassDef;import org.pentaho.di.trans.steps.userdefinedjavaclass.UserDefinedJavaClassMeta;import org.pentaho.di.www.SlaveServerJobStatus;import org.pentaho.di.www.SlaveServerTransStatus;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Lazy;import org.springframework.stereotype.Service;import javax.annotation.Resource;import java.io.*;import java.util.*;import java.util.stream.Collectors;import static com.strongdata.dataflow.core.datasource.commons.constants.UpdateType.add_scope;import static com.strongdata.dataflow.core.datasource.commons.constants.UpdateType.all_scope;@Service@Slf4jpublic class ExtractDataService { private final static String DEFINE_ALL_SCOPE = "all_scope"; private final static String DEFINE_INCREMENTAL_ADD = "incremental_add"; private final static String DEFINE_INCREMENTAL_DELETE = "incremental_delete"; private final static String DEFINE_TOTALSQL = "totalSql"; private final static String DEFINE_SELECTSQL = "selectSQL"; private final static String DEFINE_APPEND = "APPEND"; private final static String DEFINE_TRANS_ = "trans_"; private final static String DEFINE_JOB_ = "job_"; private final static String DEFINE_TRANS_ADD_ = "trans_add_"; private final static String DEFINE_JOB_ADD_ = "job_add_"; private final static String DEFINE_JOB_DELETE_ = "job_delete_"; private final static String DEFINE_TRANS_DELETE_ = "trans_delete_"; private final static String DEFINE_UTF8 = "UTF-8"; private final static String DEFINE_NATIVE = "Native"; private final static String DEFINE_ORACLE = "ORACLE"; private final static String DEFINE_STRING = "String"; private final static String DEFINE_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; private final static String DEFINE_DATAEASE_UUID = "dataease_uuid"; private final static String DEFINE_HANDLECHARSET = "handleCharset"; @Resource @Lazy private DataSetTableService dataSetTableService; @Resource private DataSetTableFieldsService dataSetTableFieldsService; @Resource private DatasourceService datasourceService; @Resource private EngineService engineService; @Resource private KettleService kettleService; @Value("${file.root.dir}") private String rootDir; //private static final String lastUpdateTime = "${__last_update_time__}"; //private static final String currentUpdateTime = "${__current_update_time__}"; private static final String separator = "|DE|"; private static final String extension = "txt"; @Value("${file.root.path:/data/kettle/}") private String root_path; @Value("${kettle.files.keep:false}") private boolean kettleFilesKeep; @Value("${extract.page.size:50000}") private Long extractPageSize; private static final String shellScript = "result=`curl --location-trusted -u %s:%s -H \"label:%s\" -H \"column_separator:%s\" -H \"columns:%s\" -H \"merge_type: %s\" -T %s -XPUT http://%s:%s/api/%s/%s/_stream_load`\n" + "if [ $? -eq 0 ] ; then\n" + " failstatus=$(echo $result | grep '\"Status\": \"Fail\"')\n" + " if [ \"x${failstatus}\" != \"x\" ];then" + " echo $result\n" + " exit 1\n" + " fi\n" + "else\n" + " echo $result\n" + " exit 1\n" + "fi\n"; private static final String shellScriptForDeleteFile = "result=`curl --location-trusted -u %s:%s -H \"label:%s\" -H \"column_separator:%s\" -H \"columns:%s\" -H \"merge_type: %s\" -T %s -XPUT http://%s:%s/api/%s/%s/_stream_load`\n" + "rm -rf %s \n" + "if [ $? -eq 0 ] ; then\n" + " failstatus=$(echo $result | grep '\"Status\": \"Fail\"')\n" + " if [ \"x${failstatus}\" != \"x\" ];then" + " echo $result\n" + " exit 1\n" + " fi\n" + "else\n" + " echo $result\n" + " exit 1\n" + "fi\n"; public void extractData(String datasetTableId, String type) { DatasetTable datasetTable = getDatasetTable(datasetTableId); if (datasetTable == null) { LogUtil.error("Can not find DatasetTable: " + datasetTableId); return; } UpdateType updateType = UpdateType.valueOf(type); Datasource datasource = new Datasource(); if (StringUtils.isNotEmpty(datasetTable.getDataSourceId())) { datasource = datasourceService.get(datasetTable.getDataSourceId()); } else { datasource.setType(datasetTable.getType()); } List<DatasetTableField> datasetTableFields = getDatasetTableFields(datasetTable.getId()); JobStatus lastExecStatus = JobStatus.Completed; Long execTime = null; if (all_scope==updateType) { try { createEngineTable(TableUtils.tableName(datasetTableId), datasetTableFields); createEngineTable(TableUtils.tmpName(TableUtils.tableName(datasetTableId)), datasetTableFields); execTime = System.currentTimeMillis(); extractData(datasetTable, datasource, datasetTableFields, DEFINE_ALL_SCOPE, null); replaceTable(TableUtils.tableName(datasetTableId)); //saveSuccessLog(datasetTableTaskLog, true); } catch (Exception e) { //saveErrorLog(datasetTableTaskLog, e, true); lastExecStatus = JobStatus.Error; execTime = null; } finally { try { deleteFile(DEFINE_ALL_SCOPE, datasetTableId); } catch (Exception ignore) { LogUtil.error(ignore); } try { //sendWebMsg(datasetTable, datasetTableTask, datasetTableTaskLog, msg); } catch (Exception ignore) { LogUtil.error(ignore); } try { updateTableStatus(datasetTableId, lastExecStatus, execTime); } catch (Exception ignore) { LogUtil.error(ignore); } try { //dataSetTableTaskService.updateTaskStatus(datasetTableTask, lastExecStatus); } catch (Exception ignore) { LogUtil.error(ignore); } try { dropDorisTable(TableUtils.tmpName(TableUtils.tableName(datasetTableId))); } catch (Exception ignore) { LogUtil.error(ignore); } } }else if(add_scope==updateType){ try { if (datasource.getType().equalsIgnoreCase(DatasourceTypes.api.name())) { extractData(datasetTable, datasource, datasetTableFields, DEFINE_INCREMENTAL_ADD, null); } } catch (Exception e) { lastExecStatus = JobStatus.Error; } finally { try { deleteFile(DEFINE_INCREMENTAL_ADD, datasetTableId); deleteFile(DEFINE_INCREMENTAL_DELETE, datasetTableId); updateTableStatus(datasetTableId, lastExecStatus, execTime); } catch (Exception ignore) { LogUtil.error(ignore); } } } } public List<DatasetTableField> getDatasetTableFields(String datasetTableId) { List<DatasetTableField> datasetTableFields = dataSetTableFieldsService.list(DatasetTableField.builder().tableId(datasetTableId).build()); datasetTableFields = datasetTableFields.stream().filter(datasetTableField -> datasetTableField.getExtField() == 0).collect(Collectors.toList()); datasetTableFields.sort((o1, o2) -> { if (o1.getColumnIndex() == null) { return -1; } if (o2.getColumnIndex() == null) { return 1; } return o1.getColumnIndex().compareTo(o2.getColumnIndex()); }); return datasetTableFields; } @SneakyThrows private void extractData(DatasetTable datasetTable, Datasource datasource, List<DatasetTableField> datasetTableFields, String extractType, String selectSQL) throws DataManageException { if (datasource.getType().equalsIgnoreCase(DatasourceTypes.api.name())) { extractApiData(datasetTable, datasource, datasetTableFields, extractType); return; } Map<String, String> sql = getSelectSQL(extractType, datasetTable, datasource, datasetTableFields, selectSQL); if (StringUtils.isNotEmpty(sql.get(DEFINE_TOTALSQL))) { DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(datasource); Provider datasourceProvider = ProviderFactory.getProvider(datasource.getType()); datasourceRequest.setQuery(sql.get(DEFINE_TOTALSQL)); List<String[]> tmpData = datasourceProvider.getData(datasourceRequest); Long totalItems = CollectionUtils.isEmpty(tmpData) ? 0 : Long.valueOf(tmpData.get(0)[0]); Long totalPage = (totalItems / extractPageSize) + (totalItems % extractPageSize > 0 ? 1 : 0); for (Long i = 0L; i < totalPage; i++) { Long offset = i * extractPageSize; Long all = offset + extractPageSize; extractDataByKettle(datasetTable, datasource, datasetTableFields, extractType, sql.get(DEFINE_SELECTSQL).replace("DE_OFFSET", offset.toString()).replace("DE_PAGE_SIZE", extractPageSize.toString()).replace("DE_ALL", all.toString())); } } else { extractDataByKettle(datasetTable, datasource, datasetTableFields, extractType, sql.get(DEFINE_SELECTSQL)); } } private void extractApiData(DatasetTable datasetTable, Datasource datasource, List<DatasetTableField> datasetTableFields, String extractType) throws DataManageException, IOException { List<ApiDefinition> lists = new Gson().fromJson(datasource.getConfiguration(), new TypeToken<ArrayList<ApiDefinition>>() { }.getType()); lists = lists.stream().filter(item -> item.getName().equalsIgnoreCase(new Gson().fromJson(datasetTable.getInfo(), DataTableInfoDTO.class).getTable())).collect(Collectors.toList()); if (CollectionUtils.isEmpty(lists)) { throw DataManageException.getException("未找到API数据表"); } if (lists.size() > 1) { throw DataManageException.getException("存在重名的API数据表"); } Provider datasourceProvider = ProviderFactory.getProvider(datasource.getType()); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(datasource); datasourceRequest.setTable(new Gson().fromJson(datasetTable.getInfo(), DataTableInfoDTO.class).getTable()); Map<String, List> result = datasourceProvider.fetchResultAndField(datasourceRequest); List<String[]> dataList = result.get("dataList"); if (engineService.isSimpleMode()) { extractDataForSimpleMode(extractType, datasetTable.getId(), dataList); return; } Datasource engine = engineService.getDeEngine(); DorisConfiguration dorisConfiguration = new Gson().fromJson(engine.getConfiguration(), DorisConfiguration.class); String columns = datasetTableFields.stream().map(DatasetTableField::getDataeaseName).collect(Collectors.joining(",")) + ",dataease_uuid"; String dataFile = null; String script = null; String streamLoadScript = ""; if (kettleFilesKeep) { streamLoadScript = shellScript; } else { streamLoadScript = shellScriptForDeleteFile; } if (DEFINE_ALL_SCOPE.equals(extractType)) { dataFile = rootDir + root_path + TableUtils.tmpName(TableUtils.tableName(datasetTable.getId())) + "." + extension; script = String.format(streamLoadScript, dorisConfiguration.getUsername(), dorisConfiguration.getPassword(), System.currentTimeMillis(), separator, columns, DEFINE_APPEND, dataFile, dorisConfiguration.getHost(), dorisConfiguration.getHttpPort(), dorisConfiguration.getDataBase(), TableUtils.tmpName(TableUtils.tableName(datasetTable.getId())), dataFile); }else{ dataFile = rootDir + root_path + TableUtils.addName(TableUtils.tableName(datasetTable.getId())) + "." + extension; script = String.format(streamLoadScript, dorisConfiguration.getUsername(), dorisConfiguration.getPassword(), System.currentTimeMillis(), separator, columns, DEFINE_APPEND, dataFile, dorisConfiguration.getHost(), dorisConfiguration.getHttpPort(), dorisConfiguration.getDataBase(), TableUtils.tableName(datasetTable.getId()), dataFile); } try (BufferedWriter bw = new BufferedWriter(new FileWriter(dataFile))) { for (String[] strings : dataList) { StringBuilder content = new StringBuilder(); for (int i = 0; i < strings.length; i++) { content.append(strings[i]).append(separator); } content = content.append(Md5Utils.md5(content.toString())); bw.write(content.toString()); bw.newLine(); } } File scriptFile = new File(rootDir + root_path + datasetTable.getId() + ".sh"); boolean re = scriptFile.createNewFile(); LogUtil.info(re); re = scriptFile.setExecutable(true); LogUtil.info(re); try (BufferedWriter scriptFileBw = new BufferedWriter(new FileWriter(root_path + datasetTable.getId() + ".sh"))) { scriptFileBw.write("#!/bin/sh"); scriptFileBw.newLine(); scriptFileBw.write(script); scriptFileBw.newLine(); } try { Process process = Runtime.getRuntime().exec(rootDir + root_path + datasetTable.getId() + ".sh"); process.waitFor(); if (process.waitFor() != 0) { BufferedReader input = new BufferedReader(new InputStreamReader(process.getErrorStream())); StringBuilder errMsg = new StringBuilder(); String line = ""; while ((line = input.readLine()) != null) { errMsg.append(line).append(System.getProperty("line.separator")); } input = new BufferedReader(new InputStreamReader(process.getInputStream())); while ((line = input.readLine()) != null) { errMsg.append(line).append(System.getProperty("line.separator")); } throw DataManageException.getException(errMsg.toString()); } } catch (Exception e) { Thread.currentThread().interrupt(); throw DataManageException.getException(e.getMessage()); } finally { File deleteFile = new File(rootDir + root_path + datasetTable.getId() + ".sh"); FileUtils.forceDelete(deleteFile); } } private void extractDataForSimpleMode(String extractType, String datasetId, List<String[]> dataList) throws DataManageException { String tableName; if (DEFINE_ALL_SCOPE.equals(extractType)) { tableName = TableUtils.tmpName(TableUtils.tableName(datasetId)); }else{ tableName = TableUtils.tableName(datasetId); } Datasource engine = engineService.getDeEngine(); JdbcProvider jdbcProvider = CommonBeanFactory.getBean(JdbcProvider.class); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(engine); DDLProvider ddlProvider = ProviderFactory.getDDLProvider(engine.getType()); int pageNumber = 100; //一次插入 100条 int totalPage; if (dataList.size() % pageNumber > 0) { totalPage = dataList.size() / pageNumber + 1; } else { totalPage = dataList.size() / pageNumber; } for (int page = 1; page <= totalPage; page++) { datasourceRequest.setQuery(ddlProvider.insertSql(tableName, dataList, page, pageNumber)); jdbcProvider.exec(datasourceRequest); } } @SneakyThrows private void extractDataByKettle(DatasetTable datasetTable, Datasource datasource, List<DatasetTableField> datasetTableFields, String extractType, String selectSQL) throws DataManageException { generateTransFile(extractType, datasetTable, datasource, datasetTableFields, selectSQL); generateJobFile(extractType, datasetTable, datasetTableFields.stream().map(DatasetTableField::getDataeaseName).collect(Collectors.joining(","))); extractData(datasetTable, extractType); } private void updateTableStatus(String datasetTableId, JobStatus jobStatus, Long execTime) { DatasetTable datasetTableRecord = new DatasetTable(); datasetTableRecord.setId(datasetTableId); datasetTableRecord.setSyncStatus(jobStatus.name()); if (execTime != null) { datasetTableRecord.setLastUpdateTime(execTime); } DatasetTableExample example = new DatasetTableExample(); example.createCriteria().andIdEqualTo(datasetTableId); dataSetTableService.updateByExampleSelective(datasetTableRecord, example); } public void createEngineTable(String tableName, List<DatasetTableField> datasetTableFields) throws DataManageException { Datasource engine = engineService.getDeEngine(); JdbcProvider jdbcProvider = CommonBeanFactory.getBean(JdbcProvider.class); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(engine); DDLProvider ddlProvider = ProviderFactory.getDDLProvider(engine.getType()); datasourceRequest.setQuery(ddlProvider.createTableSql(tableName, datasetTableFields, engine)); jdbcProvider.exec(datasourceRequest); } private void dropDorisTable(String tableName) { try { Datasource engine = engineService.getDeEngine(); JdbcProvider jdbcProvider = CommonBeanFactory.getBean(JdbcProvider.class); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(engine); DDLProvider ddlProvider = ProviderFactory.getDDLProvider(engine.getType()); datasourceRequest.setQuery(ddlProvider.dropTable(tableName)); jdbcProvider.exec(datasourceRequest); } catch (Exception ignore) { throw DataManageException.getException(ignore.getMessage()); } } private void replaceTable(String dorisTableName) throws DataManageException { Datasource engine = engineService.getDeEngine(); JdbcProvider jdbcProvider = CommonBeanFactory.getBean(JdbcProvider.class); DatasourceRequest datasourceRequest = new DatasourceRequest(); datasourceRequest.setDatasource(engine); DDLProvider ddlProvider = ProviderFactory.getDDLProvider(engine.getType()); String[] replaceTableSql = ddlProvider.replaceTable(dorisTableName).split(";"); for (int i = 0; i < replaceTableSql.length; i++) { if (StringUtils.isNotEmpty(replaceTableSql[i])) { datasourceRequest.setQuery(replaceTableSql[i]); jdbcProvider.exec(datasourceRequest); } } } private DatasetTable getDatasetTable(String datasetTableId) { for (int i = 0; i < 5; i++) { DatasetTable datasetTable = dataSetTableService.get(datasetTableId); if (datasetTable == null) { try { Thread.sleep(1000); } catch (Exception ignore) { LogUtil.error(ignore.getMessage()); } } else { return datasetTable; } } return null; } @SneakyThrows private void extractData(DatasetTable datasetTable, String extractType) throws DataManageException { if (StringUtils.isNotEmpty(datasetTable.getDataSourceId())) { datasourceService.validate(datasetTable.getDataSourceId()); } KettleFileRepository repository = CommonBeanFactory.getBean(KettleFileRepository.class); RepositoryDirectoryInterface repositoryDirectoryInterface = repository.loadRepositoryDirectoryTree(); TransMeta transMeta = null; JobMeta jobMeta = null; switch (extractType) { case DEFINE_ALL_SCOPE: jobMeta = repository.loadJob(DEFINE_JOB_ + TableUtils.tableName(datasetTable.getId()), repositoryDirectoryInterface, null, null); transMeta = repository.loadTransformation(DEFINE_TRANS_ + TableUtils.tableName(datasetTable.getId()), repositoryDirectoryInterface, null, true, ""); break; case DEFINE_INCREMENTAL_ADD: jobMeta = repository.loadJob(DEFINE_JOB_ADD_ + TableUtils.tableName(datasetTable.getId()), repositoryDirectoryInterface, null, null); transMeta = repository.loadTransformation(DEFINE_TRANS_ADD_ + TableUtils.tableName(datasetTable.getId()), repositoryDirectoryInterface, null, true, ""); break; case DEFINE_INCREMENTAL_DELETE: jobMeta = repository.loadJob(DEFINE_JOB_DELETE_ + TableUtils.tableName(datasetTable.getId()), repositoryDirectoryInterface, null, null); transMeta = repository.loadTransformation(DEFINE_TRANS_DELETE_ + TableUtils.tableName(datasetTable.getId()), repositoryDirectoryInterface, null, true, ""); break; default: break; } SlaveServer remoteSlaveServer = kettleService.getSlaveServer(); JobExecutionConfiguration jobExecutionConfiguration = new JobExecutionConfiguration(); jobExecutionConfiguration.setRemoteServer(remoteSlaveServer); jobExecutionConfiguration.setRepository(repository); TransExecutionConfiguration transExecutionConfiguration = new TransExecutionConfiguration(); transExecutionConfiguration.setRepository(repository); transExecutionConfiguration.setRemoteServer(remoteSlaveServer); String lastTranceId = Trans.sendToSlaveServer(transMeta, transExecutionConfiguration, repository, null); SlaveServerTransStatus transStatus = null; boolean executing = (null == transMeta) ? false : true; while (executing) { transStatus = remoteSlaveServer.getTransStatus(transMeta.getName(), lastTranceId, 0); executing = transStatus.isRunning() || transStatus.isWaiting(); if (!executing) break; Thread.sleep(1000); } if (null != transStatus && !transStatus.getStatusDescription().equals("Finished")) { DataManageException.throwException(transStatus.getLoggingString()); return; } executing = true; String lastCarteObjectId = Job.sendToSlaveServer(jobMeta, jobExecutionConfiguration, repository, null); SlaveServerJobStatus jobStatus = null; while (jobMeta!=null && executing) { jobStatus = remoteSlaveServer.getJobStatus(jobMeta.getName(), lastCarteObjectId, 0); executing = jobStatus.isRunning() || jobStatus.isWaiting(); if (!executing) break; Thread.sleep(1000); } if (null != jobStatus && jobStatus.getStatusDescription().equals("Finished")) { LogUtil.info(datasetTable.getId() + ": " + jobStatus.getLoggingString()); return; } else { DataManageException.throwException("获取从库状态失败"); } } @SneakyThrows private void generateJobFile(String extractType, DatasetTable datasetTable, String columnFields) throws DataManageException { if (engineService.isSimpleMode()) { return; } String outFile; String jobName = null; String script = null; Datasource dorisDatasource = engineService.getDeEngine(); DorisConfiguration dorisConfiguration = new Gson().fromJson(dorisDatasource.getConfiguration(), DorisConfiguration.class); String columns = columnFields + ",dataease_uuid"; String streamLoadScript = ""; if (kettleFilesKeep) { streamLoadScript = shellScript; } else { streamLoadScript = shellScriptForDeleteFile; } switch (extractType) { case DEFINE_ALL_SCOPE: outFile = TableUtils.tmpName(TableUtils.tableName(datasetTable.getId())); jobName = DEFINE_JOB_ + TableUtils.tableName(datasetTable.getId()); script = String.format(streamLoadScript, dorisConfiguration.getUsername(), dorisConfiguration.getPassword(), datasetTable.getId() + System.currentTimeMillis(), separator, columns, DEFINE_APPEND, rootDir + root_path + outFile + "." + extension, dorisConfiguration.getHost(), dorisConfiguration.getHttpPort(), dorisConfiguration.getDataBase(), TableUtils.tmpName(TableUtils.tableName(datasetTable.getId())), root_path + outFile + "." + extension); break; case DEFINE_INCREMENTAL_ADD: outFile = TableUtils.addName(datasetTable.getId()); jobName = DEFINE_JOB_ADD_ + TableUtils.tableName(datasetTable.getId()); script = String.format(streamLoadScript, dorisConfiguration.getUsername(), dorisConfiguration.getPassword(), datasetTable.getId() + System.currentTimeMillis(), separator, columns, DEFINE_APPEND, rootDir + root_path + outFile + "." + extension, dorisConfiguration.getHost(), dorisConfiguration.getHttpPort(), dorisConfiguration.getDataBase(), TableUtils.tableName(datasetTable.getId()), root_path + outFile + "." + extension); break; case DEFINE_INCREMENTAL_DELETE: outFile = TableUtils.deleteName(TableUtils.tableName(datasetTable.getId())); script = String.format(streamLoadScript, dorisConfiguration.getUsername(), dorisConfiguration.getPassword(), datasetTable.getId() + System.currentTimeMillis(), separator, columns, "DELETE", rootDir + root_path + outFile + "." + extension, dorisConfiguration.getHost(), dorisConfiguration.getHttpPort(), dorisConfiguration.getDataBase(), TableUtils.tableName(datasetTable.getId()), root_path + outFile + "." + extension); jobName = DEFINE_JOB_DELETE_ + TableUtils.tableName(datasetTable.getId()); break; default: break; } JobMeta jobMeta = new JobMeta(); jobMeta.setName(jobName); //start JobEntrySpecial start = new JobEntrySpecial(); start.setName("START"); start.setStart(true); JobEntryCopy startEntry = new JobEntryCopy(start); startEntry.setDrawn(true); startEntry.setLocation(100, 100); jobMeta.addJobEntry(startEntry); //exec shell JobEntryShell shell = new JobEntryShell(); shell.setScript(script); shell.insertScript = true; shell.setName("shell"); JobEntryCopy shellEntry = new JobEntryCopy(shell); shellEntry.setDrawn(true); shellEntry.setLocation(500, 100); jobMeta.addJobEntry(shellEntry); JobHopMeta transHop = new JobHopMeta(startEntry, shellEntry); transHop.setEvaluation(true); jobMeta.addJobHop(transHop); //success JobEntrySuccess success = new JobEntrySuccess(); success.setName("Success"); JobEntryCopy successEntry = new JobEntryCopy(success); successEntry.setDrawn(true); successEntry.setLocation(700, 100); jobMeta.addJobEntry(successEntry); JobHopMeta greenHop = new JobHopMeta(shellEntry, successEntry); greenHop.setEvaluation(true); jobMeta.addJobHop(greenHop); String jobXml = jobMeta.getXML(); File file = new File(rootDir + root_path + jobName + ".kjb"); FileUtils.writeStringToFile(file, jobXml, DEFINE_UTF8); }//// private String fetchSqlField(String sql, Datasource ds) throws DataManageException {// QueryProvider qp = ProviderFactory.getQueryProvider(ds.getType());// Provider datasourceProvider = ProviderFactory.getProvider(ds.getType());// DatasourceRequest datasourceRequest = new DatasourceRequest();// datasourceRequest.setDatasource(ds);// datasourceRequest.setQuery(qp.wrapSql(sql));// List<String> dorisFields = new ArrayList<>();// datasourceProvider.fetchResultField(datasourceRequest).stream().map(TableField::getFieldName).forEach(field -> {// dorisFields.add(TableUtils.columnName(field));// });// return String.join(",", dorisFields);// } private void generateTransFile(String extractType, DatasetTable datasetTable, Datasource datasource, List<DatasetTableField> datasetTableFields, String selectSQL) throws DataManageException, IOException, KettleException { if (engineService.isSimpleMode()) { return; } TransMeta transMeta = new TransMeta(); String outFile = null; DatasourceTypes datasourceType = DatasourceTypes.valueOf(datasource.getType()); DatabaseMeta dataMeta; List<StepMeta> inputSteps = new ArrayList<>(); StepMeta outputStep; StepMeta udjcStep = null; TransHopMeta hi2; String transName = null; switch (datasourceType) { case ds_doris: case mariadb: case mysql: case TiDB: case StarRocks: MysqlConfiguration mysqlConfiguration = new Gson().fromJson(datasource.getConfiguration(), MysqlConfiguration.class); dataMeta = new DatabaseMeta("db", "MYSQL", DEFINE_NATIVE, mysqlConfiguration.getHost().trim(), mysqlConfiguration.getDataBase().trim(), mysqlConfiguration.getPort().toString(), mysqlConfiguration.getUsername(), mysqlConfiguration.getPassword()); if (StringUtils.isNotEmpty(mysqlConfiguration.getExtraParams()) && mysqlConfiguration.getExtraParams().split("&").length > 0) { String[] params = mysqlConfiguration.getExtraParams().split("&"); for (int i = 0; i < params.length; i++) { dataMeta.addExtraOption("MYSQL", params[i].split("=")[0], params[i].split("=")[1]); } } transMeta.addDatabase(dataMeta); inputSteps = inputStep(transMeta, selectSQL, mysqlConfiguration); udjcStep = udjc(datasetTableFields, DatasourceTypes.mysql, mysqlConfiguration); break; case sqlServer: SqlServerConfiguration sqlServerConfiguration = new Gson().fromJson(datasource.getConfiguration(), SqlServerConfiguration.class); dataMeta = new DatabaseMeta("db", "MSSQLNATIVE", DEFINE_NATIVE, sqlServerConfiguration.getHost().trim(), sqlServerConfiguration.getDataBase(), sqlServerConfiguration.getPort().toString(), sqlServerConfiguration.getUsername(), sqlServerConfiguration.getPassword()); transMeta.addDatabase(dataMeta); inputSteps = inputStep(transMeta, selectSQL, sqlServerConfiguration); udjcStep = udjc(datasetTableFields, DatasourceTypes.sqlServer, sqlServerConfiguration); break; case pg: PgConfiguration pgConfiguration = new Gson().fromJson(datasource.getConfiguration(), PgConfiguration.class); dataMeta = new DatabaseMeta("db", "POSTGRESQL", DEFINE_NATIVE, pgConfiguration.getHost().trim(), pgConfiguration.getDataBase(), pgConfiguration.getPort().toString(), pgConfiguration.getUsername(), pgConfiguration.getPassword()); transMeta.addDatabase(dataMeta); inputSteps = inputStep(transMeta, selectSQL, pgConfiguration); udjcStep = udjc(datasetTableFields, DatasourceTypes.pg, pgConfiguration); break; case oracle: OracleConfiguration oracleConfiguration = new Gson().fromJson(datasource.getConfiguration(), OracleConfiguration.class); if (oracleConfiguration.getConnectionType().equalsIgnoreCase("serviceName")) { String database = "(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = ORACLE_HOSTNAME)(PORT = ORACLE_PORT))(CONNECT_DATA = (SERVER = DEDICATED)(SERVICE_NAME = ORACLE_SERVICE_NAME )))".replace("ORACLE_HOSTNAME", oracleConfiguration.getHost()).replace("ORACLE_PORT", oracleConfiguration.getPort().toString()).replace("ORACLE_SERVICE_NAME", oracleConfiguration.getDataBase()); dataMeta = new DatabaseMeta("db", DEFINE_ORACLE, DEFINE_NATIVE, "", database, "-1", oracleConfiguration.getUsername(), oracleConfiguration.getPassword()); } else { dataMeta = new DatabaseMeta("db", DEFINE_ORACLE, DEFINE_NATIVE, oracleConfiguration.getHost().trim(), oracleConfiguration.getDataBase(), oracleConfiguration.getPort().toString(), oracleConfiguration.getUsername(), oracleConfiguration.getPassword()); } transMeta.addDatabase(dataMeta); inputSteps = inputStep(transMeta, selectSQL, oracleConfiguration); udjcStep = udjc(datasetTableFields, DatasourceTypes.oracle, oracleConfiguration); break; case ck: CHConfiguration chConfiguration = new Gson().fromJson(datasource.getConfiguration(), CHConfiguration.class); dataMeta = new DatabaseMeta("db", DEFINE_ORACLE, DEFINE_NATIVE, chConfiguration.getHost().trim(), chConfiguration.getDataBase().trim(), chConfiguration.getPort().toString(), chConfiguration.getUsername(), chConfiguration.getPassword()); dataMeta.setDatabaseType("Clickhouse"); transMeta.addDatabase(dataMeta); inputSteps = inputStep(transMeta, selectSQL, chConfiguration); udjcStep = udjc(datasetTableFields, DatasourceTypes.ck, chConfiguration); break; case db2: Db2Configuration db2Configuration = new Gson().fromJson(datasource.getConfiguration(), Db2Configuration.class); dataMeta = new DatabaseMeta("db", "DB2", DEFINE_NATIVE, db2Configuration.getHost().trim(), db2Configuration.getDataBase().trim(), db2Configuration.getPort().toString(), db2Configuration.getUsername(), db2Configuration.getPassword()); dataMeta.setDatabaseType("DB2"); transMeta.addDatabase(dataMeta); inputSteps = inputStep(transMeta, selectSQL, db2Configuration); udjcStep = udjc(datasetTableFields, DatasourceTypes.db2, db2Configuration); break; case excel: inputSteps = excelInputStep(datasetTable.getInfo(), datasetTableFields); udjcStep = udjc(datasetTableFields, DatasourceTypes.excel, null); break; default: break; } switch (extractType) { case DEFINE_ALL_SCOPE: transName = DEFINE_TRANS_ + TableUtils.tableName(datasetTable.getId()); outFile = TableUtils.tmpName(TableUtils.tableName(datasetTable.getId())); transMeta.setName(transName); break; case DEFINE_INCREMENTAL_ADD: transName = DEFINE_TRANS_ADD_ + TableUtils.tableName(datasetTable.getId()); outFile = TableUtils.addName(datasetTable.getId()); transMeta.setName(transName); break; case DEFINE_INCREMENTAL_DELETE: transName = DEFINE_TRANS_DELETE_ + TableUtils.tableName(datasetTable.getId()); outFile = TableUtils.deleteName(TableUtils.tableName(datasetTable.getId())); transMeta.setName(transName); break; default: break; } outputStep = outputStep(outFile, datasetTableFields, datasource); for (StepMeta inputStep : inputSteps) { TransHopMeta hi1 = new TransHopMeta(inputStep, udjcStep); transMeta.addTransHop(hi1); transMeta.addStep(inputStep); } hi2 = new TransHopMeta(udjcStep, outputStep); transMeta.addTransHop(hi2); transMeta.addStep(udjcStep); transMeta.addStep(outputStep); String transXml = transMeta.getXML(); File file = new File(rootDir + root_path + transName + ".ktr"); FileUtils.writeStringToFile(file, transXml, DEFINE_UTF8); } private Map<String, String> getSelectSQL(String extractType, DatasetTable datasetTable, Datasource datasource, List<DatasetTableField> datasetTableFields, String selectSQL) { Map<String, String> sql = new HashMap<>(); if (extractType.equalsIgnoreCase(DEFINE_ALL_SCOPE) && datasetTable.getType().equalsIgnoreCase(DatasetType.DB.name())) { String tableName = new Gson().fromJson(datasetTable.getInfo(), DataTableInfoDTO.class).getTable(); QueryProvider qp = ProviderFactory.getQueryProvider(datasource.getType()); sql.put(DEFINE_SELECTSQL, qp.createRawQuerySQL(tableName, datasetTableFields, datasource)); sql.put(DEFINE_TOTALSQL, qp.getTotalCount(true, tableName, datasource)); } if (extractType.equalsIgnoreCase(DEFINE_ALL_SCOPE) && datasetTable.getType().equalsIgnoreCase(DatasetType.SQL.name())) { DataTableInfoDTO dataTableInfoDTO = new Gson().fromJson(datasetTable.getInfo(), DataTableInfoDTO.class); selectSQL = dataTableInfoDTO.getSql(); if (dataTableInfoDTO.isBase64Encryption()) { selectSQL = new String(Base64.getDecoder().decode(selectSQL)); } QueryProvider qp = ProviderFactory.getQueryProvider(datasource.getType()); sql.put(DEFINE_TOTALSQL, qp.getTotalCount(false, selectSQL, datasource)); sql.put(DEFINE_SELECTSQL, qp.createRawQuerySQLAsTmp(selectSQL, datasetTableFields)); } if (!extractType.equalsIgnoreCase(DEFINE_ALL_SCOPE)) { QueryProvider qp = ProviderFactory.getQueryProvider(datasource.getType()); sql.put(DEFINE_TOTALSQL, qp.getTotalCount(false, selectSQL, datasource)); sql.put(DEFINE_SELECTSQL, qp.createRawQuerySQLAsTmp(selectSQL, datasetTableFields)); } return sql; } private List<StepMeta> inputStep(TransMeta transMeta, String selectSQL, JdbcConfiguration jdbcConfiguration) { log.debug(jdbcConfiguration.toString()); TableInputMeta tableInput = new TableInputMeta(); DatabaseMeta database = transMeta.findDatabase(DatasetType.DB.name()); tableInput.setDatabaseMeta(database); tableInput.setSQL(selectSQL); StepMeta fromStep = new StepMeta("TableInput", "Data Input", tableInput); fromStep.setDraw(true); fromStep.setLocation(100, 100); List<StepMeta> inputSteps = new ArrayList<>(); inputSteps.add(fromStep); return inputSteps; } private List<StepMeta> excelInputStep(String Info, List<DatasetTableField> datasetTableFields) { List<StepMeta> inputSteps = new ArrayList<>(); DataTableInfoDTO dataTableInfoDTO = new Gson().fromJson(Info, DataTableInfoDTO.class); List<ExcelSheetData> excelSheetDataList = dataTableInfoDTO.getExcelSheetDataList(); List<String> sheetNames = new ArrayList<>(); int size = 1; for (ExcelSheetData excelSheetData : excelSheetDataList) { StepMeta fromStep = null; String suffix = excelSheetData.getPath().substring(excelSheetDataList.get(0).getPath().lastIndexOf('.') + 1); if (StringUtils.equalsIgnoreCase(suffix, "csv")) { CsvInputMeta csvInputMeta = new CsvInputMeta(); csvInputMeta.setFilename(excelSheetData.getPath()); csvInputMeta.setHeaderPresent(true); csvInputMeta.setBufferSize("10000"); csvInputMeta.setDelimiter(","); TextFileInputField[] fields = new TextFileInputField[datasetTableFields.size()]; for (int i = 0; i < datasetTableFields.size(); i++) { TextFileInputField field = new TextFileInputField(); field.setName(datasetTableFields.get(i).getDataeaseName()); if (datasetTableFields.get(i).getDeExtractType() == 1) { field.setType(ValueMetaBase.getType(DEFINE_STRING)); field.setFormat(DEFINE_DATE_FORMAT); } else { field.setType(ValueMetaBase.getType(DEFINE_STRING)); } fields[i] = field; } csvInputMeta.setInputFields(fields); fromStep = new StepMeta("CsvInput", "Data Input " + size, csvInputMeta); fromStep.setDraw(true); fromStep.setLocation(100, 100 * size); inputSteps.add(fromStep); } else { List<String> files = new ArrayList<>(); files.add(excelSheetData.getPath()); List<String> filesRequired = new ArrayList<>(); filesRequired.add("Y"); ExcelInputMeta excelInputMeta = new ExcelInputMeta(); sheetNames.add(excelSheetData.getExcelLabel()); if (StringUtils.equalsIgnoreCase(suffix, "xlsx")) { excelInputMeta.setSpreadSheetType(SpreadSheetType.SAX_POI); excelInputMeta.setSheetName(sheetNames.toArray(new String[sheetNames.size()])); } if (StringUtils.equalsIgnoreCase(suffix, "xls")) { excelInputMeta.setSpreadSheetType(SpreadSheetType.JXL); excelInputMeta.setSheetName(sheetNames.toArray(new String[sheetNames.size()])); } excelInputMeta.setPassword("Encrypted"); excelInputMeta.setFileName(files.toArray(new String[files.size()])); excelInputMeta.setFileRequired(filesRequired.toArray(new String[filesRequired.size()])); excelInputMeta.setStartsWithHeader(true); excelInputMeta.setIgnoreEmptyRows(true); ExcelInputField[] fields = new ExcelInputField[datasetTableFields.size()]; for (int i = 0; i < datasetTableFields.size(); i++) { ExcelInputField field = new ExcelInputField(); field.setName(datasetTableFields.get(i).getDataeaseName()); if (datasetTableFields.get(i).getDeExtractType() == 1) { field.setType(DEFINE_STRING); field.setFormat(DEFINE_DATE_FORMAT); } else { field.setType(DEFINE_STRING); } fields[i] = field; } excelInputMeta.setField(fields); fromStep = new StepMeta("ExcelInput", "Data Input " + size, excelInputMeta); fromStep.setDraw(true); fromStep.setLocation(100, 100 * size); inputSteps.add(fromStep); } size++; } return inputSteps; } private StepMeta outputStep(String dorisOutputTable, List<DatasetTableField> datasetTableFields, Datasource datasource) { TextFileOutputMeta textFileOutputMeta = new TextFileOutputMeta(); textFileOutputMeta.setEncoding(DEFINE_UTF8); textFileOutputMeta.setHeaderEnabled(false); textFileOutputMeta.setFilename(rootDir + root_path + dorisOutputTable); textFileOutputMeta.setSeparator(separator); textFileOutputMeta.setExtension(extension); if (datasource.getType().equalsIgnoreCase(DatasourceTypes.oracle.name())) { TextFileField[] outputFields = new TextFileField[datasetTableFields.size() + 1]; for (int i = 0; i < datasetTableFields.size(); i++) { TextFileField textFileField = new TextFileField(); textFileField.setName(datasetTableFields.get(i).getOriginName()); textFileField.setType(DEFINE_STRING); outputFields[i] = textFileField; } TextFileField textFileField = new TextFileField(); textFileField.setName(DEFINE_DATAEASE_UUID); textFileField.setType(DEFINE_STRING); outputFields[datasetTableFields.size()] = textFileField; textFileOutputMeta.setOutputFields(outputFields); } else if (datasource.getType().equalsIgnoreCase(DatasourceTypes.sqlServer.name()) || datasource.getType().equalsIgnoreCase(DatasourceTypes.pg.name()) || datasource.getType().equalsIgnoreCase(DatasourceTypes.mysql.name())) { TextFileField[] outputFields = new TextFileField[datasetTableFields.size() + 1]; for (int i = 0; i < datasetTableFields.size(); i++) { TextFileField textFileField = new TextFileField(); textFileField.setName(datasetTableFields.get(i).getDataeaseName()); if (datasetTableFields.get(i).getDeExtractType().equals(DeTypeConstants.DE_TIME)) { textFileField.setType(DEFINE_STRING); textFileField.setFormat(DEFINE_DATE_FORMAT); } else { textFileField.setType(DEFINE_STRING); } outputFields[i] = textFileField; } TextFileField textFileField = new TextFileField(); textFileField.setName(DEFINE_DATAEASE_UUID); textFileField.setType(DEFINE_STRING); outputFields[datasetTableFields.size()] = textFileField; textFileOutputMeta.setOutputFields(outputFields); } else if (datasource.getType().equalsIgnoreCase(DatasourceTypes.excel.name())) { TextFileField[] outputFields = new TextFileField[datasetTableFields.size() + 1]; for (int i = 0; i < datasetTableFields.size(); i++) { TextFileField textFileField = new TextFileField(); textFileField.setName(datasetTableFields.get(i).getDataeaseName()); if (datasetTableFields.get(i).getDeExtractType().equals(DeTypeConstants.DE_INT)) { textFileField.setType("Integer"); textFileField.setFormat("0"); } else { textFileField.setType(DEFINE_STRING); } outputFields[i] = textFileField; } TextFileField textFileField = new TextFileField(); textFileField.setName(DEFINE_DATAEASE_UUID); textFileField.setType(DEFINE_STRING); outputFields[datasetTableFields.size()] = textFileField; textFileOutputMeta.setOutputFields(outputFields); } else { textFileOutputMeta.setOutputFields(new TextFileField[0]); } StepMeta outputStep = new StepMeta("TextFileOutput", "TextFileOutput", textFileOutputMeta); outputStep.setLocation(600, 100); outputStep.setDraw(true); return outputStep; } private StepMeta udjc(List<DatasetTableField> datasetTableFields, DatasourceTypes datasourceType, JdbcConfiguration jdbcConfiguration) { StringBuilder handleBinaryTypeCode = new StringBuilder(); String excelCompletion = ""; for (DatasetTableField datasetTableField : datasetTableFields) { if (datasetTableField.getDeExtractType().equals(DeTypeConstants.DE_BINARY)) { handleBinaryTypeCode.append("\n").append(handleBinaryType.replace("FIELD", datasetTableField.getDataeaseName())); } } UserDefinedJavaClassMeta userDefinedJavaClassMeta = new UserDefinedJavaClassMeta(); List<UserDefinedJavaClassMeta.FieldInfo> fields = new ArrayList<>(); UserDefinedJavaClassMeta.FieldInfo fieldInfo = new UserDefinedJavaClassMeta.FieldInfo(DEFINE_DATAEASE_UUID, ValueMetaInterface.TYPE_STRING, -1, -1); fields.add(fieldInfo); userDefinedJavaClassMeta.setFieldInfo(fields); List<UserDefinedJavaClassDef> definitions = new ArrayList<>(); String tmp_code = code.replace("handleWraps", handleWraps).replace("handleBinaryType", handleBinaryTypeCode.toString()); String Column_Fields; if (datasourceType.equals(DatasourceTypes.oracle) || datasourceType.equals(DatasourceTypes.db2)) { Column_Fields = datasetTableFields.stream().map(DatasetTableField::getOriginName).collect(Collectors.joining(",")); String charset = null; String targetCharset = DEFINE_UTF8; if (StringUtils.isNotEmpty(jdbcConfiguration.getCharset()) && !jdbcConfiguration.getCharset().equalsIgnoreCase("Default")) { charset = jdbcConfiguration.getCharset(); } if (StringUtils.isNotEmpty(jdbcConfiguration.getTargetCharset()) && !jdbcConfiguration.getTargetCharset().equalsIgnoreCase("Default")) { targetCharset = jdbcConfiguration.getTargetCharset(); } if (StringUtils.isNotEmpty(charset)) { String varcharFields = datasetTableFields.stream().filter(datasetTableField -> datasetTableField.getDeExtractType() == 0).map(DatasetTableField::getOriginName).collect(Collectors.joining(",")); tmp_code = tmp_code.replace(DEFINE_HANDLECHARSET, handleCharset.replace("Datasource_Charset", charset).replace("Target_Charset", targetCharset).replace("varcharFields", varcharFields)); } else { tmp_code = tmp_code.replace(DEFINE_HANDLECHARSET, ""); } } else { Column_Fields = datasetTableFields.stream().map(DatasetTableField::getDataeaseName).collect(Collectors.joining(",")); tmp_code = tmp_code.replace(DEFINE_HANDLECHARSET, ""); } if (datasourceType.equals(DatasourceTypes.excel)) { tmp_code = tmp_code.replace("handleExcelIntColumn", handleExcelIntColumn).replace("Column_Fields", Column_Fields) .replace("ExcelCompletion", excelCompletion); } else { tmp_code = tmp_code.replace("handleExcelIntColumn", "").replace("Column_Fields", Column_Fields) .replace("ExcelCompletion", ""); } UserDefinedJavaClassDef userDefinedJavaClassDef = new UserDefinedJavaClassDef(UserDefinedJavaClassDef.ClassType.TRANSFORM_CLASS, "Processor", tmp_code); userDefinedJavaClassDef.setActive(true); definitions.add(userDefinedJavaClassDef); userDefinedJavaClassMeta.replaceDefinitions(definitions); StepMeta userDefinedJavaClassStep = new StepMeta("UserDefinedJavaClass", "UserDefinedJavaClass", userDefinedJavaClassMeta); userDefinedJavaClassStep.setLocation(300, 100); userDefinedJavaClassStep.setDraw(true); return userDefinedJavaClassStep; } public void deleteFile(String type, String dataSetTableId) { if (kettleFilesKeep) { return; } String transName = null; String jobName = null; String fileName = null; switch (type) { case DEFINE_ALL_SCOPE: transName = DEFINE_TRANS_ + TableUtils.tableName(dataSetTableId); jobName = DEFINE_JOB_ + TableUtils.tableName(dataSetTableId); fileName = TableUtils.tmpName(TableUtils.tableName(dataSetTableId)); break; case DEFINE_INCREMENTAL_ADD: transName = DEFINE_TRANS_ADD_ + TableUtils.tableName(dataSetTableId); jobName = DEFINE_JOB_ADD_ + TableUtils.tableName(dataSetTableId); fileName = TableUtils.addName(TableUtils.tableName(dataSetTableId)); break; case DEFINE_INCREMENTAL_DELETE: transName = DEFINE_TRANS_DELETE_ + TableUtils.tableName(dataSetTableId); jobName = DEFINE_JOB_DELETE_ + TableUtils.tableName(dataSetTableId); fileName = TableUtils.deleteName(TableUtils.tableName(dataSetTableId)); break; default: break; } deleteFile(rootDir + root_path + fileName + "." + extension); deleteFile(rootDir + root_path + jobName + ".kjb"); deleteFile(rootDir + root_path + transName + ".ktr"); } private void deleteExcelFile(DatasetTable datasetTable, List<String> datasetTableIds) { List<DatasetTable> datasetTables = dataSetTableService.list(datasetTableIds); for (ExcelSheetData excelSheetData : new Gson().fromJson(datasetTable.getInfo(), DataTableInfoDTO.class).getExcelSheetDataList()) { Boolean allIsFinished = true; for (DatasetTable table : datasetTables) { for (ExcelSheetData data : new Gson().fromJson(table.getInfo(), DataTableInfoDTO.class).getExcelSheetDataList()) { if ((data.getPath().equalsIgnoreCase(excelSheetData.getPath())) && StringUtils.isEmpty(table.getSyncStatus()) || table.getSyncStatus().equalsIgnoreCase(JobStatus.Underway.name())) { allIsFinished = false; } } } if (allIsFinished) { deleteFile(excelSheetData.getPath()); } else { try { Thread.sleep(5000); } catch (Exception ignore) { LogUtil.error(ignore.getMessage()); } deleteExcelFile(datasetTable, datasetTableIds); } } } private void deleteFile(String filePath) { if (StringUtils.isEmpty(filePath)) { return; } try { File file = new File(filePath); FileUtils.forceDelete(file); } catch (Exception e) { LogUtil.error(e.getMessage()); } } private final static String handleBinaryType = " \t\tif(\"FIELD\".equalsIgnoreCase(filed)){\n" + " get(Fields.Out, filed).setValue(r, \"\");\n" + " get(Fields.Out, filed).getValueMeta().setType(2);\n" + " \t}"; private final static String handleExcelIntColumn = " \t\tif(tmp != null && tmp.endsWith(\".0\")){\n" + " try {\n" + " Long.valueOf(tmp.substring(0, tmp.length()-2));\n" + " get(Fields.Out, filed).setValue(r, tmp.substring(0, tmp.length()-2));\n" + " get(Fields.Out, filed).getValueMeta().setType(2);\n" + " }catch (Exception e){}\n" + " }"; private final static String handleWraps = " if(tmp != null && ( tmp.contains(\"\\r\") || tmp.contains(\"\\n\"))){\n" + "\t\t\ttmp = tmp.trim();\n" + " tmp = tmp.replaceAll(\"\\r\",\" \");\n" + " tmp = tmp.replaceAll(\"\\n\",\" \");\n" + " get(Fields.Out, filed).setValue(r, tmp);\n" + " } \n"; private final static String handleCharset = "\tif(tmp != null && Arrays.asList(\"varcharFields\".split(\",\")).contains(filed)){\n" + " \t\t\ttry {\n" + "\t\t\t\tget(Fields.Out, filed).setValue(r, new String(tmp.getBytes(\"Datasource_Charset\"), \"Target_Charset\"));\n" + " \t\t}catch (Exception e){}\n" + "\t\t}"; private final static String code = "import org.pentaho.di.core.row.ValueMetaInterface;\n" + "import java.util.List;\n" + "import java.io.File;\n" + "import java.security.MessageDigest;\n" + "import java.util.ArrayList;\n" + "import java.util.Arrays;\n" + "import java.util.List;\n" + "import java.util.concurrent.ExecutorService;\n" + "import java.util.concurrent.Executors;\n" + "import org.pentaho.di.core.util.StringUtil;\n" + "\n" + "public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {\n" + " if (first) {\n" + " first = false;\n" + " }\n" + "\n" + " Object[] r = getRow();\n" + "\n" + " if (r == null) {\n" + " setOutputDone();\n" + " return false;\n" + "}\n" + "\n" + " r = createOutputRow(r, data.outputRowMeta.size());\n" + " String str = \"\";\n" + "\n" + " List<String> fields = Arrays.asList(\"Column_Fields\".split(\",\"));\n" + " for (String filed : fields) {\n" + " String tmp = get(Fields.In, filed).getString(r);\n" + "handleCharset \n" + "handleWraps \n" + "ExcelCompletion \n" + "handleBinaryType \n" + "handleExcelIntColumn \n" + " str = str + tmp;\n" + " }\n" + "\n" + " String md5 = md5(str);\n" + " get(Fields.Out, \"dataease_uuid\").setValue(r, md5);\n" + "\n" + " putRow(data.outputRowMeta, r);\n" + "\n" + " return true;\n" + "}\n" + "\n" + " private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};\n" + " private static final String UTF_8 = \"UTF-8\";\n" + " public static String md5(String src) {\n" + " return md5(src, UTF_8);\n" + " }\n" + " public static String md5(String src, String charset) {\n" + " try {\n" + " byte[] strTemp = charset == null || charset.equals(\"\") ? src.getBytes() : src.getBytes(charset);\n" + " MessageDigest mdTemp = MessageDigest.getInstance(\"MD5\");\n" + " mdTemp.update(strTemp);\n" + "\n" + " byte[] md = mdTemp.digest();\n" + " int j = md.length;\n" + " char[] str = new char[j * 2];\n" + " int k = 0;\n" + "\n" + " for (byte byte0 : md) {\n" + " str[k++] = HEX_DIGITS[byte0 >>> 4 & 0xf];\n" + " str[k++] = HEX_DIGITS[byte0 & 0xf];\n" + " }\n" + "\n" + " return new String(str);\n" + " } catch (Exception e) {\n" + " throw DataManageException.getException(\"MD5 encrypt error:\", e);\n" + " }\n" + " }\n" + "\n" + " public String generateStr(int size, String[] d ){\n" + " String str = null;\n" + " for(int i=0;i<size;i++){\n" + " str = str + d[i];\n" + " }\n" + " return str;\n" + " }";}
package cn.chinatowercom.dataflow.datasource.service;import com.google.gson.Gson;import com.strongdata.dataflow.core.datasource.entity.DeEngine;import com.strongdata.dataflow.core.datasource.entity.DeEngineExample;import com.strongdata.dataflow.core.datasource.entity.HttpClientConfig;import com.strongdata.dataflow.core.datasource.entity.ResultHolder;import com.strongdata.dataflow.core.datasource.entity.dto.KettleDTO;import com.strongdata.dataflow.core.datasource.exception.DataManageException;import com.strongdata.dataflow.core.datasource.mapper.DeEngineMapper;import com.strongdata.dataflow.core.datasource.utils.HttpClientUtil;import org.apache.commons.collections4.CollectionUtils;import org.apache.commons.lang3.StringUtils;import org.pentaho.di.cluster.SlaveServer;import org.springframework.core.env.Environment;import org.springframework.stereotype.Service;import javax.annotation.Resource;import java.security.SecureRandom;import java.util.Base64;import java.util.List;import java.util.UUID;import java.util.stream.Collectors;@Servicepublic class KettleService { private final static String DEFINE_SUCCESS = "Success"; private final static String DEFINE_CLUSTER = "cluster"; @Resource private Environment env; @Resource private DeEngineMapper deEngineMapper; @Resource private EngineService engineService; public ResultHolder save(DeEngine kettle) throws DataManageException { try { validate(new Gson().fromJson(kettle.getConfiguration(), KettleDTO.class)); kettle.setStatus(DEFINE_SUCCESS); }catch (Exception e){ kettle.setStatus("Error"); } if (StringUtils.isEmpty(kettle.getId())) { kettle.setId(UUID.randomUUID().toString()); kettle.setType("kettle"); deEngineMapper.insert(kettle); } else { deEngineMapper.updateByPrimaryKeyWithBLOBs(kettle); } return ResultHolder.success(kettle); } public void delete(String id){ deEngineMapper.deleteByPrimaryKey(id); } public void validate(KettleDTO kettleDTO) throws DataManageException { HttpClientConfig httpClientConfig = new HttpClientConfig(); String authValue = "Basic " + Base64.getUrlEncoder().encodeToString((kettleDTO.getUser() + ":" + kettleDTO.getPasswd()).getBytes()); httpClientConfig.addHeader("Authorization", authValue); String response = HttpClientUtil.get("http://" + kettleDTO.getCarte() + ":" + kettleDTO.getPort() + "/kettle/status/", httpClientConfig); } public ResultHolder validate(String id) { DeEngine kettle = deEngineMapper.selectByPrimaryKey(id); try { validate(new Gson().fromJson(kettle.getConfiguration(), KettleDTO.class)); kettle.setStatus(DEFINE_SUCCESS); deEngineMapper.updateByPrimaryKeyWithBLOBs(kettle); return ResultHolder.success(kettle); }catch (Exception e){ kettle.setStatus("Error"); deEngineMapper.updateByPrimaryKeyWithBLOBs(kettle); return ResultHolder.error(e.getMessage()); } } public List<DeEngine> pageList(){ DeEngineExample deEngineExample = new DeEngineExample(); deEngineExample.createCriteria().andTypeEqualTo("kettle"); return deEngineMapper.selectByExampleWithBLOBs(deEngineExample); } public void updateKettleStatus(){ if(!engineService.isClusterMode()){ return; } List<DeEngine>kettles = pageList(); kettles.forEach(kettle -> { validate(kettle.getId()); }); } public SlaveServer getSlaveServer() throws DataManageException{ SlaveServer remoteSlaveServer = new SlaveServer(); if(engineService.isLocalMode()){ remoteSlaveServer.setHostname(env.getProperty("carte.host", "127.0.0.1")); remoteSlaveServer.setPort(env.getProperty("carte.port", "8080")); remoteSlaveServer.setUsername(env.getProperty("carte.user", DEFINE_CLUSTER)); remoteSlaveServer.setPassword(env.getProperty("carte.passwd", DEFINE_CLUSTER)); }else { List<DeEngine> kettles = pageList().stream().filter(kettle -> kettle.getStatus() != null && kettle.getStatus().equalsIgnoreCase(DEFINE_SUCCESS)) .collect(Collectors.toList()); if(CollectionUtils.isEmpty(kettles)){ throw DataManageException.getException("No valid kettle service."); }// DeEngine kettle = kettles.get(new Random().nextInt(kettles.size())); DeEngine kettle = kettles.get(new SecureRandom().nextInt(kettles.size())); KettleDTO kettleDTO = new Gson().fromJson(kettle.getConfiguration(), KettleDTO.class); remoteSlaveServer.setHostname(kettleDTO.getCarte()); remoteSlaveServer.setPort(kettleDTO.getPort()); remoteSlaveServer.setUsername(kettleDTO.getUser()); remoteSlaveServer.setPassword(kettleDTO.getPasswd()); } return remoteSlaveServer; } public boolean isKettleRunning() { if(engineService.isLocalMode()){ try { KettleDTO kettleDTO = new KettleDTO(); kettleDTO.setCarte(env.getProperty("carte.host", "127.0.0.1")); kettleDTO.setPort(env.getProperty("carte.port", "8080")); kettleDTO.setUser(env.getProperty("carte.user", DEFINE_CLUSTER)); kettleDTO.setPasswd(env.getProperty("carte.passwd", DEFINE_CLUSTER)); validate(kettleDTO); return true; }catch (Exception e){ return false; } } if(engineService.isClusterMode()){ List<DeEngine> kettles = pageList().stream().filter(kettle -> kettle.getStatus() != null && kettle.getStatus().equalsIgnoreCase(DEFINE_SUCCESS)) .collect(Collectors.toList()); if(CollectionUtils.isEmpty(kettles)){ return false; }else { return true; } } return false; }}
package cn.chinatowercom.dataflow.datasource.service;import com.strongdata.dataflow.core.datasource.entity.dto.RelationDTO;import com.strongdata.dataflow.core.datasource.mapper.ExtDataSetTableMapper;import com.strongdata.dataflow.core.datasource.mapper.ExtDataSourceMapper;import org.springframework.stereotype.Service;import javax.annotation.Resource;import java.util.List;/** * @author WiSoniC * @date 2023年2月28日15:17:17 */@Servicepublic class RelationService { @Resource private ExtDataSourceMapper extDataSourceMapper; @Resource private ExtDataSetTableMapper extDataSetTableMapper; public List<RelationDTO> getRelationForDatasource(String datasourceId, Long userId) { return extDataSourceMapper.queryDatasourceRelation(datasourceId, userId); } public RelationDTO getRelationForDataset(String datasetId, Long userId) { return extDataSetTableMapper.queryDatasetRelation(datasetId, userId); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.datasource.service;import com.strongdata.dataflow.core.datasource.entity.SysProjectDatasource;import com.strongdata.dataflow.core.datasource.mapper.SysProjectDatasourceMapper;import org.springframework.stereotype.Service;import javax.annotation.Resource;/** * 项目和数据源关联表 * * @author hj * @date 2023-03-20 10:44:05 */@Servicepublic class SysProjectDatasourceService { @Resource private SysProjectDatasourceMapper sysProjectDatasourceMapper; /** * 保存数据源和项目对应表 * * @return */ public int saveProjectDatasource(SysProjectDatasource sysProjectDatasource) { return sysProjectDatasourceMapper.saveProjectDatasource(sysProjectDatasource); } /** * 保存数据源和项目对应表 * * @return */ public void delProjectDatasource(SysProjectDatasource sysProjectDatasource) { sysProjectDatasourceMapper.delProjectDatasource(sysProjectDatasource); }}
package cn.chinatowercom.dataflow.datasource.service;import cn.chinatowercom.dataflow.datasource.service.abstractservice.LoginLimitXpackService;import com.strongdata.dataflow.core.datasource.commons.constants.ParamConstants;import com.strongdata.dataflow.core.datasource.entity.BasicInfo;import com.strongdata.dataflow.core.datasource.entity.SystemParameter;import com.strongdata.dataflow.core.datasource.entity.SystemParameterExample;import com.strongdata.dataflow.core.datasource.mapper.SystemParameterMapper;import com.strongdata.dataflow.core.datasource.utils.EncryptUtils;import com.strongdata.dataflow.core.datasource.utils.SpringContextUtil;import org.apache.commons.collections4.CollectionUtils;import org.apache.commons.lang3.StringUtils;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import javax.annotation.Resource;import java.util.List;import java.util.Map;@Service@Transactional(rollbackFor = Exception.class)public class SystemParameterService { private static final String STRING_TRUE = "true"; private static final String STRING_FLASE = "false"; @Resource private SystemParameterMapper systemParameterMapper; public BasicInfo basicInfo() { List<SystemParameter> paramList = this.getParamList("basic"); List<SystemParameter> homePageList = this.getParamList("ui.openHomePage"); List<SystemParameter> marketPageList = this.getParamList("ui.openMarketPage"); List<SystemParameter> loginLimitList = this.getParamList("loginlimit"); paramList.addAll(homePageList); paramList.addAll(marketPageList); paramList.addAll(loginLimitList); BasicInfo result = new BasicInfo(); result.setOpenHomePage("true"); Map<String, LoginLimitXpackService> beansOfType = SpringContextUtil.getApplicationContext().getBeansOfType((LoginLimitXpackService.class)); Boolean loginLimitPluginLoaded = beansOfType.keySet().size() > 0; if (!CollectionUtils.isEmpty(paramList)) { for (SystemParameter param : paramList) { result = doTraversalCollForBasicInfo(param, loginLimitPluginLoaded); } } return result; } private BasicInfo doTraversalCollForBasicInfo(SystemParameter param, boolean loginLimitPluginLoaded) { BasicInfo result = new BasicInfo(); if (StringUtils.equals(param.getParamKey(), ParamConstants.BASIC.FRONT_TIME_OUT.getValue())) { result.setFrontTimeOut(param.getParamValue()); } if (StringUtils.equals(param.getParamKey(), ParamConstants.BASIC.MSG_TIME_OUT.getValue())) { result.setMsgTimeOut(param.getParamValue()); } if (StringUtils.equals(param.getParamKey(), ParamConstants.BASIC.LOG_TIME_OUT.getValue())) { result.setLogTimeOut(param.getParamValue()); } if (StringUtils.equals(param.getParamKey(), ParamConstants.BASIC.DEFAULT_LOGIN_TYPE.getValue())) { String paramValue = param.getParamValue(); result.setLoginType(StringUtils.isNotBlank(paramValue) ? Integer.parseInt(paramValue) : 0); } if (StringUtils.equals(param.getParamKey(), ParamConstants.BASIC.OPEN_HOME_PAGE.getValue())) { boolean open = StringUtils.equals(STRING_TRUE, param.getParamValue()); result.setOpenHomePage(open ? STRING_TRUE : STRING_FLASE); } if (StringUtils.equals(param.getParamKey(), ParamConstants.BASIC.OPEN_MARKET_PAGE.getValue())) { boolean open = StringUtils.equals(STRING_TRUE, param.getParamValue()); result.setOpenMarketPage(open ? STRING_TRUE : STRING_FLASE); } if (StringUtils.equals(param.getParamKey(), ParamConstants.BASIC.TEMPLATE_MARKET_ULR.getValue())) { result.setTemplateMarketUlr(param.getParamValue()); } if (StringUtils.equals(param.getParamKey(), ParamConstants.BASIC.TEMPLATE_ACCESS_KEY.getValue())) { result.setTemplateAccessKey(param.getParamValue()); } if (StringUtils.equals(param.getParamKey(), ParamConstants.BASIC.DS_CHECK_INTERVAL.getValue())) { result.setDsCheckInterval(param.getParamValue()); } if (StringUtils.equals(param.getParamKey(), ParamConstants.BASIC.DS_CHECK_INTERVAL_TYPE.getValue())) { result.setDsCheckIntervalType(param.getParamValue()); } if (loginLimitPluginLoaded) { if (StringUtils.equals(param.getParamKey(), ParamConstants.BASIC.LOGIN_LIMIT_LIMITTIMES.getValue())) { String paramValue = param.getParamValue(); if (StringUtils.isNotBlank(paramValue)) { result.setLimitTimes(Integer.parseInt(paramValue)); } } if (StringUtils.equals(param.getParamKey(), ParamConstants.BASIC.LOGIN_LIMIT_RELIEVETIMES.getValue())) { String paramValue = param.getParamValue(); if (StringUtils.isNotBlank(paramValue)) { result.setRelieveTimes(Integer.parseInt(paramValue)); } } if (StringUtils.equals(param.getParamKey(), ParamConstants.BASIC.LOGIN_LIMIT_OPEN.getValue())) { boolean open = StringUtils.equals(STRING_TRUE, param.getParamValue()); result.setOpen(open ? STRING_TRUE : STRING_FLASE); } if (StringUtils.equals(param.getParamKey(), ParamConstants.BASIC.SCAN_CREATE_USER.getValue())) { boolean open = StringUtils.equals(STRING_TRUE, param.getParamValue()); result.setScanCreateUser(open ? STRING_TRUE : STRING_FLASE); } } return result; } public List<SystemParameter> getParamList(String type) { SystemParameterExample example = new SystemParameterExample(); example.createCriteria().andParamKeyLike(type + "%"); return systemParameterMapper.selectByExample(example); } public String getVersion() { return System.getenv("MS_VERSION"); } public void saveLdap(List<SystemParameter> parameters) { SystemParameterExample example = new SystemParameterExample(); parameters.forEach(param -> { if (param.getParamKey().equals(ParamConstants.LDAP.PASSWORD.getValue())) { String string = EncryptUtils.aesEncrypt(param.getParamValue()).toString(); param.setParamValue(string); } example.createCriteria().andParamKeyEqualTo(param.getParamKey()); if (systemParameterMapper.countByExample(example) > 0) { systemParameterMapper.updateByPrimaryKey(param); } else { systemParameterMapper.insert(param); } example.clear(); }); } public String getValue(String key) { SystemParameter param = systemParameterMapper.selectByPrimaryKey(key); if (param == null) { return null; } return param.getParamValue(); }}
package cn.chinatowercom.dataflow.datasource.service;import com.strongdata.dataflow.core.datasource.entity.Datasource;import com.strongdata.dataflow.core.datasource.entity.dto.VAuthModelDTO;import com.strongdata.dataflow.core.datasource.entity.request.VAuthModelRequest;import com.strongdata.dataflow.core.datasource.mapper.DatasourceMapper;import com.strongdata.dataflow.core.datasource.mapper.ExtVAuthModelMapper;import com.strongdata.dataflow.core.datasource.utils.TreeUtils;import org.apache.commons.collections4.CollectionUtils;import org.springframework.stereotype.Service;import javax.annotation.Resource;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.stream.Collectors;/** * Author: wx * Date: 2023/2/24 * Description: */@Servicepublic class VAuthModelService { @Resource private ExtVAuthModelMapper extVAuthModelMapper; @Resource private DatasourceMapper datasourceMapper; public List<VAuthModelDTO> queryAuthModelByIds(String modelType, List<String> ids) { if (CollectionUtils.isEmpty(ids)) { return new ArrayList<>(); } List<VAuthModelDTO> result = extVAuthModelMapper.queryAuthModelByIds("1", modelType, ids); if (CollectionUtils.isEmpty(result)) { return new ArrayList<>(); } else { return result; } } public List<VAuthModelDTO> queryAuthModel(VAuthModelRequest request) { request.setUserId("1"); List<VAuthModelDTO> result = extVAuthModelMapper.queryAuthModel(request); if (CollectionUtils.isEmpty(result)) { return new ArrayList<>(); } //查询出项目下的数据源信息 List<Datasource> datasourceList = datasourceMapper.getProjectDatasourceList(request.getProjectId()); List<String> datasourceIds = datasourceList.stream().map(ds -> ds.getId()).collect(Collectors.toList()); //过滤数据集和数据集分组 result = result.stream().filter(vAuthModelDTO -> (("leaf".equalsIgnoreCase(vAuthModelDTO.getNodeType()) && datasourceIds.contains(vAuthModelDTO.getDataSourceId())) || "spine".equalsIgnoreCase(vAuthModelDTO.getNodeType()))).collect(Collectors.toList()); if (request.isClearEmptyDir()) { List<VAuthModelDTO> vAuthModelDTOS = TreeUtils.mergeTree(result); setAllLeafs(vAuthModelDTOS); removeEmptyDir(vAuthModelDTOS); return vAuthModelDTOS; } return TreeUtils.mergeTree(result); } private void removeEmptyDir(List<VAuthModelDTO> result) { if (CollectionUtils.isEmpty(result)) { return; } Iterator<VAuthModelDTO> iterator = result.listIterator(); while (iterator.hasNext()) { VAuthModelDTO tmp = iterator.next(); if ("spine".equalsIgnoreCase(tmp.getNodeType()) && tmp.getAllLeafs() == 0) { iterator.remove(); } else { removeEmptyDir(tmp.getChildren()); } } } private void setAllLeafs(List<VAuthModelDTO> result) { for (VAuthModelDTO vAuthModelDTO : result) { if (CollectionUtils.isEmpty(vAuthModelDTO.getChildren())) { vAuthModelDTO.setAllLeafs(0); continue; } long leafs = 0L; for (VAuthModelDTO child : vAuthModelDTO.getChildren()) { if ("leaf".equalsIgnoreCase(child.getNodeType())) { leafs = leafs + 1; } else { leafs = +leafs + getLeafs(child); } } vAuthModelDTO.setAllLeafs(leafs); } } private long getLeafs(VAuthModelDTO child) { long leafs = 0L; if (CollectionUtils.isEmpty(child.getChildren())) { child.setAllLeafs(0); return leafs; } for (VAuthModelDTO childChild : child.getChildren()) { if ("leaf".equalsIgnoreCase(childChild.getNodeType())) { leafs = leafs + 1; } else { leafs = +leafs + getLeafs(childChild); } } child.setAllLeafs(leafs); return leafs; }}
package cn.chinatowercom.dataflow.datasource.service.abstractservice;import com.strongdata.dataflow.core.datasource.entity.DataSourceType;/** * @author hj * @Description * @createTime 2023/02/17 17:18 */public abstract class AbstractDatasourceService extends PluginComponentService { abstract public DataSourceType getDataSourceType();}
package cn.chinatowercom.dataflow.datasource.service.abstractservice;import com.strongdata.dataflow.core.datasource.entity.dto.SysSettingDto;import com.strongdata.dataflow.core.datasource.entity.response.CasSaveResult;import javax.servlet.ServletContext;import java.util.List;/** * @author hj * * @createTime 2023/02/17 16:16 */public abstract class CasXpackService extends PluginComponentService { public abstract List<SysSettingDto> casSettings(); public abstract CasSaveResult save(List<SysSettingDto> parameters); public Boolean supportCas() { return false; } public abstract void checkCasStatus(ServletContext servletContext); public abstract void setEnabled(Boolean valid); public abstract String logout();}
package cn.chinatowercom.dataflow.datasource.service.abstractservice;import com.strongdata.dataflow.core.datasource.entity.LoginLimitInfo;import com.strongdata.dataflow.core.datasource.entity.dto.SysSettingDto;import java.util.List;/** * @author hj * * @createTime 2023/02/17 16:13 */public abstract class LoginLimitXpackService extends PluginComponentService { public abstract LoginLimitInfo info(); public abstract void save(List<SysSettingDto> settings); public abstract Boolean isOpen();}
package cn.chinatowercom.dataflow.datasource.service.abstractservice;import com.strongdata.dataflow.core.datasource.entity.StaticResource;import org.apache.commons.lang3.StringUtils;import java.io.InputStream;import java.util.ArrayList;import java.util.List;/** * @author hj * * @createTime 2023/02/17 15:08 */public abstract class PluginComponentService { private static final String SPLIT = "."; private static final String DEFAULT_SUFFIX = "js"; private static final List emptyResult = new ArrayList(); public abstract List<String> components(); public List<StaticResource> staticResources(){ return emptyResult; } protected abstract InputStream readContent(String name); public InputStream vueResource(String name) { return vueResource(name, DEFAULT_SUFFIX); } public InputStream vueResource(String name, String suffix) { if (StringUtils.isEmpty(name) || StringUtils.isEmpty(suffix)) return null; String lastName = SPLIT + suffix; if (!name.endsWith(lastName)) name += lastName; return readContent(name); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.iam.controller;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.core.security.annotation.NoAuth;import com.strongdata.dataflow.iam.api.dto.UserInfo;import com.strongdata.dataflow.iam.api.entity.SysUser;import cn.chinatowercom.dataflow.iam.service.AppService;import cn.chinatowercom.dataflow.iam.service.SysUserService;import io.swagger.annotations.Api;import lombok.AllArgsConstructor;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * @author wildwind * @date 2022/3/16 移动端登录 */@RestController@AllArgsConstructor@RequestMapping("/app")@Api(value = "app", tags = "手机管理模块")public class AppController { private final AppService appService; private final SysUserService userService; @NoAuth(value = false) @GetMapping("/{mobile}") public R<Boolean> sendSmsCode(@PathVariable String mobile) { return appService.sendSmsCode(mobile); } /** * 获取指定用户全部信息 * @param phone 手机号 * @return 用户信息 */ @NoAuth @GetMapping("/info/{phone}") public R<UserInfo> infoByMobile(@PathVariable String phone) { SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getPhone, phone)); if (user == null) { return R.failed(String.format("用户信息为空 %s", phone)); } return R.ok(userService.getUserInfo(user)); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.iam.controller;import cn.hutool.core.lang.tree.Tree;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;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 com.strongdata.dataflow.iam.api.entity.SysDept;import cn.chinatowercom.dataflow.iam.service.SysDeptService;import io.swagger.annotations.Api;import lombok.RequiredArgsConstructor;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.*;import javax.validation.Valid;import java.util.List;/** * <p> * 部门管理 前端控制器 * </p> * * @author wildwind * @since 2019/2/1 */@RestController@RequiredArgsConstructor@RequestMapping("/dept")@Api(value = "dept", tags = "部门管理模块")public class DeptController { private final SysDeptService sysDeptService; /** * 通过ID查询 * @param id ID * @return SysDept */ @GetMapping("/{id:\\d+}") public R<SysDept> getById(@PathVariable Long id) { return R.ok(sysDeptService.getById(id)); } /** * 返回树形菜单集合 * @return 树形菜单 */ @GetMapping(value = "/tree") public R<List<Tree<Long>>> listDeptTrees() { return R.ok(sysDeptService.listDeptTrees()); } /** * 返回当前用户树形菜单集合 * @return 树形菜单 */ @GetMapping(value = "/user-tree") public R<List<Tree<Long>>> listCurrentUserDeptTrees() { return R.ok(sysDeptService.listCurrentUserDeptTrees()); } /** * 添加 * @param sysDept 实体 * @return success/false */ @SysLog("添加部门") @PostMapping @PreAuthorize("@pms.hasPermission('sys_dept_add')") public R<Boolean> save(@Valid @RequestBody SysDept sysDept) { return R.ok(sysDeptService.saveDept(sysDept)); } /** * 删除 * @param id ID * @return success/false */ @SysLog("删除部门") @DeleteMapping("/{id:\\d+}") @PreAuthorize("@pms.hasPermission('sys_dept_del')") public R<Boolean> removeById(@PathVariable Long id) { return R.ok(sysDeptService.removeDeptById(id)); } /** * 编辑 * @param sysDept 实体 * @return success/false */ @SysLog("编辑部门") @PutMapping @PreAuthorize("@pms.hasPermission('sys_dept_edit')") public R<Boolean> update(@Valid @RequestBody SysDept sysDept) { return R.ok(sysDeptService.updateDeptById(sysDept)); } /** * 根据部门名查询部门信息 * @param deptname 部门名 * @return */ @GetMapping("/details/{deptname}") public R<SysDept> user(@PathVariable String deptname) { SysDept condition = new SysDept(); condition.setName(deptname); return R.ok(sysDeptService.getOne(new QueryWrapper<>(condition))); } /** * 查收子级id列表 * @return 返回子级id列表 */ @NoAuth @GetMapping(value = "/child-id/{deptId:\\d+}") public R<List<Long>> listChildDeptId(@PathVariable Long deptId) { return R.ok(sysDeptService.listChildDeptId(deptId)); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.iam.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.constant.CacheConstants;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.core.log.annotation.SysLog;import com.strongdata.dataflow.iam.api.entity.SysDict;import com.strongdata.dataflow.iam.api.entity.SysDictItem;import cn.chinatowercom.dataflow.iam.service.SysDictItemService;import cn.chinatowercom.dataflow.iam.service.SysDictService;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 wildwind * @since 2022-03-19 */@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 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 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 updateById(@RequestBody SysDictItem sysDictItem) { sysDictItemService.updateDictItem(sysDictItem); return R.ok(); } /** * 通过id删除字典项 * @param id id * @return R */ @SysLog("删除字典项") @DeleteMapping("/item/{id:\\d+}") public R removeDictItemById(@PathVariable Long id) { sysDictItemService.removeDictItem(id); return R.ok(); } @SysLog("清除字典缓存") @DeleteMapping("/cache") @PreAuthorize("@pms.hasPermission('sys_dict_del')") public R clearDictCache() { sysDictService.clearDictCache(); return R.ok(); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.iam.controller;import cn.hutool.core.io.IoUtil;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 com.strongdata.dataflow.core.security.annotation.NoAuth;import com.strongdata.dataflow.iam.api.entity.SysFile;import cn.chinatowercom.dataflow.iam.service.SysFileService;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import lombok.AllArgsConstructor;import lombok.SneakyThrows;import org.springframework.core.io.ClassPathResource;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.*;import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;/** * 文件管理 * * @author wildwind * @date 2022-03-11 *///@RestController@AllArgsConstructor@RequestMapping("/sys-file")@Api(value = "sys-file", tags = "文件管理")public class FileController { private final SysFileService sysFileService; /** * 分页查询 * @param page 分页对象 * @param sysFile 文件管理 * @return */ @ApiOperation(value = "分页查询", notes = "分页查询") @GetMapping("/page") public R<IPage<SysFile>> getSysFilePage(Page page, SysFile sysFile) { return R.ok(sysFileService.page(page, Wrappers.query(sysFile))); } /** * 通过id删除文件管理 * @param id id * @return R */ @ApiOperation(value = "通过id删除文件管理", notes = "通过id删除文件管理") @SysLog("删除文件管理") @DeleteMapping("/{id:\\d+}") @PreAuthorize("@pms.hasPermission('sys_file_del')") public R<Boolean> removeById(@PathVariable Long id) { return R.ok(sysFileService.deleteFile(id)); } /** * 上传文件 文件名采用uuid,避免原始文件名中带"-"符号导致下载的时候解析出现异常 * @param file 资源 * @return R(/ admin / bucketName / filename) */ @PostMapping(value = "/upload") public R upload(@RequestPart("file") MultipartFile file) { return sysFileService.uploadFile(file); } /** * 获取文件 * @param bucket 桶名称 * @param fileName 文件空间/名称 * @param response * @return */ @NoAuth(false) @GetMapping("/{bucket}/{fileName}") public void file(@PathVariable String bucket, @PathVariable String fileName, HttpServletResponse response) { sysFileService.getFile(bucket, fileName, response); } /** * 获取本地(resources)文件 * @param fileName 文件名称 * @param response 本地文件 */ @SneakyThrows @GetMapping("/local/{fileName}") public void localFile(@PathVariable String fileName, HttpServletResponse response) { ClassPathResource resource = new ClassPathResource("file/" + fileName); response.setContentType("application/octet-stream; charset=UTF-8"); IoUtil.copy(resource.getInputStream(), response.getOutputStream()); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.iam.controller;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.core.security.annotation.NoAuth;import com.strongdata.dataflow.iam.api.dto.SysLogDTO;import com.strongdata.dataflow.iam.api.entity.SysLog;import cn.chinatowercom.dataflow.iam.service.SysLogService;import com.strongdata.rill.plus.excel.annotation.DownloadExcel;import io.swagger.annotations.Api;import lombok.RequiredArgsConstructor;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.*;import javax.validation.Valid;import java.util.List;/** * <p> * 日志表 前端控制器 * </p> * * @author wildwind * @since 2022/3/1 */@RestController@RequiredArgsConstructor@RequestMapping("/log")@Api(value = "log", tags = "日志管理模块")public class LogController { private final SysLogService sysLogService; /** * 简单分页查询 * @param page 分页对象 * @param sysLog 系统日志 * @return */ @GetMapping("/page") public R<IPage<SysLog>> getLogPage(Page page, SysLogDTO sysLog) { return R.ok(sysLogService.getLogByPage(page, sysLog)); } /** * 删除日志 * @param id ID * @return success/false */ @DeleteMapping("/{id:\\d+}") @PreAuthorize("@pms.hasPermission('sys_log_del')") public R<Boolean> removeById(@PathVariable Long id) { return R.ok(sysLogService.removeById(id)); } /** * 插入日志 * @param sysLog 日志实体 * @return success/false */ @NoAuth @PostMapping public R<Boolean> save(@Valid @RequestBody SysLog sysLog) { return R.ok(sysLogService.save(sysLog)); } /** * 导出excel 表格 * @param sysLog 查询条件 * @return EXCEL */ @DownloadExcel @GetMapping("/export") @PreAuthorize("@pms.hasPermission('sys_log_import_export')") public List<SysLog> export(SysLogDTO sysLog) { return sysLogService.getLogList(sysLog); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.iam.controller;import cn.hutool.core.lang.tree.Tree;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.core.log.annotation.SysLog;import com.strongdata.dataflow.core.security.util.SecurityUtils;import com.strongdata.dataflow.iam.api.entity.SysMenu;import cn.chinatowercom.dataflow.iam.service.SysMenuService;import io.swagger.annotations.Api;import lombok.RequiredArgsConstructor;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.*;import javax.validation.Valid;import java.util.Collection;import java.util.List;import java.util.Set;import java.util.stream.Collectors;/** * @author wildwind * @date 2022/3/31 */@RestController@RequiredArgsConstructor@RequestMapping("/menu")@Api(value = "menu", tags = "菜单管理模块")public class MenuController { private final SysMenuService sysMenuService; /** * 返回当前用户的树形菜单集合 * @param parentId 父节点ID * @return 当前用户的树形菜单 */ @GetMapping public R<List<Tree<Long>>> getUserMenu(Long parentId) { // 获取符合条件的菜单 Set<SysMenu> menuSet = SecurityUtils.getRoles().stream().map(sysMenuService::findMenuByRoleId) .flatMap(Collection::stream).collect(Collectors.toSet()); return R.ok(sysMenuService.filterMenu(menuSet, parentId)); } /** * 返回树形菜单集合 * @param lazy 是否是懒加载 * @param parentId 父节点ID * @return 树形菜单 */ @GetMapping(value = "/tree") public R<List<Tree<Long>>> getTree(boolean lazy, Long parentId) { return R.ok(sysMenuService.treeMenu(lazy, parentId)); } /** * 返回角色的菜单集合 * @param roleId 角色ID * @return 属性集合 */ @GetMapping("/tree/{roleId}") public R<List<Long>> getRoleTree(@PathVariable Long roleId) { return R.ok( sysMenuService.findMenuByRoleId(roleId).stream().map(SysMenu::getMenuId).collect(Collectors.toList())); } /** * 通过ID查询菜单的详细信息 * @param id 菜单ID * @return 菜单详细信息 */ @GetMapping("/{id:\\d+}") public R<SysMenu> getById(@PathVariable Long id) { return R.ok(sysMenuService.getById(id)); } /** * 新增菜单 * @param sysMenu 菜单信息 * @return 含ID 菜单信息 */ @SysLog("新增菜单") @PostMapping @PreAuthorize("@pms.hasPermission('sys_menu_add')") public R<SysMenu> save(@Valid @RequestBody SysMenu sysMenu) { sysMenuService.save(sysMenu); return R.ok(sysMenu); } /** * 删除菜单 * @param id 菜单ID * @return success/false */ @SysLog("删除菜单") @DeleteMapping("/{id:\\d+}") @PreAuthorize("@pms.hasPermission('sys_menu_del')") public R<Boolean> removeById(@PathVariable Long id) { return R.ok(sysMenuService.removeMenuById(id)); } /** * 更新菜单 * @param sysMenu * @return */ @SysLog("更新菜单") @PutMapping @PreAuthorize("@pms.hasPermission('sys_menu_edit')") public R<Boolean> update(@Valid @RequestBody SysMenu sysMenu) { return R.ok(sysMenuService.updateMenuById(sysMenu)); } /** * 清除菜单缓存 */ @SysLog("清除菜单缓存") @DeleteMapping("/cache") @PreAuthorize("@pms.hasPermission('sys_menu_del')") public R clearMenuCache() { sysMenuService.clearMenuCache(); return R.ok(); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.iam.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 com.strongdata.dataflow.core.security.annotation.NoAuth;import com.strongdata.dataflow.iam.api.entity.SysOauthClientDetails;import cn.chinatowercom.dataflow.iam.service.SysOauthClientDetailsService;import io.swagger.annotations.Api;import lombok.RequiredArgsConstructor;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.*;import javax.validation.Valid;import java.util.List;/** * <p> * 前端控制器 * </p> * * @author wildwind * @since 2022-03-15 */@RestController@RequiredArgsConstructor@RequestMapping("/client")@Api(value = "client", tags = "客户端管理模块")public class OauthClientDetailsController { private final SysOauthClientDetailsService sysOauthClientDetailsService; /** * 通过ID查询 * @param clientId 客户端id * @return SysOauthClientDetails */ @NoAuth @GetMapping("/{clientId}") public R<List<SysOauthClientDetails>> getByClientId(@PathVariable String clientId) { return R.ok(sysOauthClientDetailsService .list(Wrappers.<SysOauthClientDetails>lambdaQuery().eq(SysOauthClientDetails::getClientId, clientId))); } /** * 简单分页查询 * @param page 分页对象 * @param sysOauthClientDetails 系统终端 * @return */ @GetMapping("/page") public R<IPage<SysOauthClientDetails>> getOauthClientDetailsPage(Page page, SysOauthClientDetails sysOauthClientDetails) { return R.ok(sysOauthClientDetailsService.page(page, Wrappers.query(sysOauthClientDetails))); } /** * 添加 * @param sysOauthClientDetails 实体 * @return success/false */ @SysLog("添加终端") @PostMapping @PreAuthorize("@pms.hasPermission('sys_client_add')") public R<Boolean> add(@Valid @RequestBody SysOauthClientDetails sysOauthClientDetails) { return R.ok(sysOauthClientDetailsService.save(sysOauthClientDetails)); } /** * 删除 * @param id ID * @return success/false */ @SysLog("删除终端") @DeleteMapping("/{id}") @PreAuthorize("@pms.hasPermission('sys_client_del')") public R<Boolean> removeById(@PathVariable String id) { return R.ok(sysOauthClientDetailsService.removeClientDetailsById(id)); } /** * 编辑 * @param sysOauthClientDetails 实体 * @return success/false */ @SysLog("编辑终端") @PutMapping @PreAuthorize("@pms.hasPermission('sys_client_edit')") public R<Boolean> update(@Valid @RequestBody SysOauthClientDetails sysOauthClientDetails) { return R.ok(sysOauthClientDetailsService.updateClientDetailsById(sysOauthClientDetails)); } @SysLog("清除终端缓存") @DeleteMapping("/cache") @PreAuthorize("@pms.hasPermission('sys_client_del')") public R clearClientCache() { sysOauthClientDetailsService.clearClientCache(); return R.ok(); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.iam.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 com.strongdata.dataflow.iam.api.entity.SysRole;import com.strongdata.dataflow.iam.api.vo.RoleVo;import cn.chinatowercom.dataflow.iam.service.SysRoleMenuService;import cn.chinatowercom.dataflow.iam.service.SysRoleService;import io.swagger.annotations.Api;import lombok.RequiredArgsConstructor;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.*;import javax.validation.Valid;import java.util.List;/** * @author wildwind * @date 2022/3/1 */@RestController@RequiredArgsConstructor@RequestMapping("/role")@Api(value = "role", tags = "角色管理模块")public class RoleController { private final SysRoleService sysRoleService; private final SysRoleMenuService sysRoleMenuService; /** * 通过ID查询角色信息 * @param id ID * @return 角色信息 */ @GetMapping("/{id:\\d+}") public R<SysRole> getById(@PathVariable Long id) { return R.ok(sysRoleService.getById(id)); } /** * 添加角色 * @param sysRole 角色信息 * @return success、false */ @SysLog("添加角色") @PostMapping @PreAuthorize("@pms.hasPermission('sys_role_add')") public R<Boolean> save(@Valid @RequestBody SysRole sysRole) { return R.ok(sysRoleService.save(sysRole)); } /** * 修改角色 * @param sysRole 角色信息 * @return success/false */ @SysLog("修改角色") @PutMapping @PreAuthorize("@pms.hasPermission('sys_role_edit')") public R<Boolean> update(@Valid @RequestBody SysRole sysRole) { return R.ok(sysRoleService.updateById(sysRole)); } /** * 删除角色 * @param id * @return */ @SysLog("删除角色") @DeleteMapping("/{id:\\d+}") @PreAuthorize("@pms.hasPermission('sys_role_del')") public R<Boolean> removeById(@PathVariable Long id) { return R.ok(sysRoleService.removeRoleById(id)); } /** * 获取角色列表 * @return 角色列表 */ @GetMapping("/list") public R<List<SysRole>> listRoles() { return R.ok(sysRoleService.list(Wrappers.emptyWrapper())); } /** * 分页查询角色信息 * @param page 分页对象 * @return 分页对象 */ @GetMapping("/page") public R<IPage<SysRole>> getRolePage(Page page) { return R.ok(sysRoleService.page(page, Wrappers.emptyWrapper())); } /** * 更新角色菜单 * @param roleVo 角色对象 * @return success、false */ @SysLog("更新角色菜单") @PutMapping("/menu") @PreAuthorize("@pms.hasPermission('sys_role_perm')") public R<Boolean> saveRoleMenus(@RequestBody RoleVo roleVo) { SysRole sysRole = sysRoleService.getById(roleVo.getRoleId()); return R.ok(sysRoleMenuService.saveRoleMenus(sysRole.getRoleCode(), roleVo.getRoleId(), roleVo.getMenuIds())); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.iam.controller;import cn.hutool.core.util.ObjectUtil;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.dataflow.core.base.constant.SecurityConstants;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.iam.api.feign.RemoteTokenService;import io.swagger.annotations.Api;import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.*;import java.util.Map;import java.util.concurrent.TimeUnit;/** * @author wildwind * @date 2022/3/4 getTokenPage 管理 */@RestController@RequiredArgsConstructor@RequestMapping("/token")@Api(value = "token", tags = "令牌管理模块")@Slf4jpublic class TokenController { private final RemoteTokenService remoteTokenService; private final RedisTemplate redisTemplate; /** * 分页token 信息 * @param params 参数集 * @return token集合 */ @GetMapping("/page") public R token(@RequestParam Map<String, Object> params) { return remoteTokenService.getTokenPage(params, SecurityConstants.FROM_IN); } /** * 删除 * @param id ID * @return success/false */ @DeleteMapping("/{id}") @PreAuthorize("@pms.hasPermission('sys_token_del')") public R<Boolean> delete(@PathVariable String id) { return remoteTokenService.removeToken(id, SecurityConstants.FROM_IN); } /** * 针对业务系统通过URL跳转链接访问入口,基于redis设置Key,控制同一条请求于5分钟内不允许重复执行 * @return */ @GetMapping("/setLoginByUrlKey") public R<Page> setLoginByUrlKey(@RequestParam("randomStr") String randomStr) { String key = "LoginByUrl" + randomStr; Object object = redisTemplate.opsForValue().get(key); if(ObjectUtil.isEmpty(object)) { redisTemplate.opsForValue().set(key, randomStr, 5, TimeUnit.MINUTES); log.info("针对业务系统通过URL跳转链接访问入口,基于redis设置Key,控制同一条请求于5分钟内不允许重复执行. key: {}", key); } return R.ok(); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.iam.controller;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;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 com.strongdata.dataflow.core.security.annotation.NoAuth;import com.strongdata.dataflow.core.security.util.SecurityUtils;import com.strongdata.dataflow.iam.api.dto.UserDTO;import com.strongdata.dataflow.iam.api.dto.UserInfo;import com.strongdata.dataflow.iam.api.entity.SysDept;import com.strongdata.dataflow.iam.api.entity.SysUser;import com.strongdata.dataflow.iam.api.vo.UserExcelVO;import com.strongdata.dataflow.iam.api.vo.UserInfoVO;import com.strongdata.dataflow.iam.api.vo.UserVO;import cn.chinatowercom.dataflow.iam.service.SysDeptService;import cn.chinatowercom.dataflow.iam.service.SysUserService;import com.strongdata.rill.plus.excel.annotation.DownloadExcel;import com.strongdata.rill.plus.excel.annotation.UploadExcel;import io.swagger.annotations.Api;import lombok.RequiredArgsConstructor;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.validation.BindingResult;import org.springframework.web.bind.annotation.*;import javax.validation.Valid;import java.util.List;import java.util.Set;/** * @author wildwind * @date 2022/3/1 */@RestController@RequiredArgsConstructor@RequestMapping("/user")@Api(value = "user", tags = "用户管理模块")public class UserController { private final SysUserService userService; private final SysDeptService sysDeptService; /** * 获取当前用户全部信息 * @return 用户信息 */ @GetMapping(value = { "/info" }) public R<UserInfoVO> info() { String username = SecurityUtils.getUser().getUsername(); SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, username)); if (user == null) { return R.failed("获取当前用户信息失败"); } SysDept dept = null; user.setDeptName((dept = sysDeptService.getById(user.getDeptId()))!=null?dept.getName():null); UserInfo userInfo = userService.getUserInfo(user); UserInfoVO vo = new UserInfoVO(); vo.setSysUser(userInfo.getSysUser()); vo.setRoles(userInfo.getRoles()); vo.setPermissions(userInfo.getPermissions()); return R.ok(vo); } /** * 获取指定用户全部信息 * @return 用户信息 */ @NoAuth @GetMapping("/info/{username}") public R<UserInfo> info(@PathVariable String username) { SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, username)); if (user == null) { return R.failed(String.format("用户信息为空 %s", username)); } SysDept dept = null; user.setDeptName((dept = sysDeptService.getById(user.getDeptId()))!=null?dept.getName():null); return R.ok(userService.getUserInfo(user)); } /** * 根据部门id,查询对应的用户 id 集合 * @param deptIds 部门id 集合 * @return 用户 id 集合 */ @NoAuth @GetMapping("/ids") public R<List<Long>> listUserIdByDeptIds(@RequestParam("deptIds") Set<Long> deptIds) { return R.ok(userService.listUserIdByDeptIds(deptIds)); } /** * 通过ID查询用户信息 * @param id ID * @return 用户信息 */ @GetMapping("/{id:\\d+}") public R<UserVO> user(@PathVariable Long id) { return R.ok(userService.getUserVoById(id)); } /** * 根据用户名查询用户信息 * @param username 用户名 * @return */ @GetMapping("/details/{username}") public R<SysUser> user(@PathVariable String username) { SysUser condition = new SysUser(); condition.setUsername(username); return R.ok(userService.getOne(new QueryWrapper<>(condition))); } /** * 删除用户信息 * @param id ID * @return R */ @SysLog("删除用户信息") @DeleteMapping("/{id:\\d+}") @PreAuthorize("@pms.hasPermission('sys_user_del')") public R<Boolean> userDel(@PathVariable Long id) { SysUser sysUser = userService.getById(id); return R.ok(userService.removeUserById(sysUser)); } /** * 添加用户 * @param userDto 用户信息 * @return success/false */ @SysLog("添加用户") @PostMapping @PreAuthorize("@pms.hasPermission('sys_user_add')") public R<Boolean> user(@RequestBody UserDTO userDto) { return R.ok(userService.saveUser(userDto)); } /** * 更新用户信息 * @param userDto 用户信息 * @return R */ @SysLog("更新用户信息") @PutMapping @PreAuthorize("@pms.hasPermission('sys_user_edit')") public R<Boolean> updateUser(@Valid @RequestBody UserDTO userDto) { return R.ok(userService.updateUser(userDto)); } /** * 分页查询用户 * @param page 参数集 * @param userDTO 查询参数列表 * @return 用户集合 */ @GetMapping("/page") public R<IPage<List<UserVO>>> getUserPage(Page page, UserDTO userDTO) { return R.ok(userService.getUserWithRolePage(page, userDTO)); } /** * 修改个人信息 * @param userDto userDto * @return success/false */ @SysLog("修改个人信息") @PutMapping("/edit") public R<Boolean> updateUserInfo(@Valid @RequestBody UserDTO userDto) { return R.ok(userService.updateUserInfo(userDto)); } /** * @param username 用户名称 * @return 上级部门用户列表 */ @GetMapping("/ancestor/{username}") public R<List<SysUser>> listAncestorUsers(@PathVariable String username) { return R.ok(userService.listAncestorUsersByUsername(username)); } /** * 导出excel 表格 * @param userDTO 查询条件 * @return */ @DownloadExcel @GetMapping("/export") @PreAuthorize("@pms.hasPermission('sys_user_import_export')") public List<UserExcelVO> export(UserDTO userDTO) { return userService.listUser(userDTO); } /** * 导入用户 * @param excelVOList 用户列表 * @param bindingResult 错误信息列表 * @return R */ @PostMapping("/import") @PreAuthorize("@pms.hasPermission('sys_user_import_export')") public R importUser(@UploadExcel List<UserExcelVO> excelVOList, BindingResult bindingResult) { return userService.importUser(excelVOList, bindingResult); }}
package cn.chinatowercom.dataflow.iam.controller;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.strongdata.dataflow.core.base.constant.enums.UserInfoStatusEnum;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 com.strongdata.dataflow.iam.api.dto.UserInfo;import com.strongdata.dataflow.iam.api.entity.SysUser;import com.strongdata.dataflow.iam.api.entity.WechatEnterpriseUserInfo;import cn.chinatowercom.dataflow.iam.service.SysUserService;import cn.chinatowercom.dataflow.iam.service.WechatEnterpriseService;import io.swagger.annotations.Api;import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;import org.springframework.web.bind.annotation.*;/** * @功能描述:企业微信相关业务 * @作 者:suichuanguo * @创建时间:2022-05-24 10:50 **/@RestController@RequiredArgsConstructor@RequestMapping("/wechatEnterprise")@Api(value = "wechatEnterprise", tags = "企业微信相关管理")@Slf4jpublic class WechatEnterpriseController { private final SysUserService userService; private final WechatEnterpriseService wechatEnterpriseService; /** * @desc 用户信息管理 * @author suichuanguo * @time 2022/5/24 11:06 * @param * @return */ @SysLog("保存企业微信用户信息") @NoAuth @PostMapping("/saveThirdUserInfo") public R saveThirdUserInfo(@RequestBody WechatEnterpriseUserInfo userInfo){ if (userInfo == null) { return R.failed(String.format("微信用户信息为空")); } return R.ok(wechatEnterpriseService.saveThirdUserInfo(userInfo)); } /** * 获取指定用户全部信息 * @param id 用户id * @return 用户信息 */ @NoAuth @GetMapping("/userInfo/{id}") public R<UserInfo> getThirdUserInfoById(@PathVariable String id) { WechatEnterpriseUserInfo userInfo = wechatEnterpriseService.getOne( Wrappers.<WechatEnterpriseUserInfo>query().lambda().eq(WechatEnterpriseUserInfo::getThirdUserId, id)); if(userInfo == null|| !UserInfoStatusEnum.NORMAL.getType().equals(String.valueOf(userInfo.getStatus()))){ return R.failed(String.format("不存在此用户")); } SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUserId, userInfo.getUserId())); if (user == null) { log.info("用户信息为空"); return R.failed(String.format("用户信息为空 %s", id)); } return R.ok(userService.getUserInfo(user)); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.iam.service.impl;import cn.chinatowercom.dataflow.iam.service.AppService;import cn.hutool.core.collection.CollUtil;import cn.hutool.core.util.RandomUtil;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.strongdata.dataflow.core.base.constant.CacheConstants;import com.strongdata.dataflow.core.base.constant.SecurityConstants;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.iam.api.entity.SysUser;import cn.chinatowercom.dataflow.iam.mapper.SysUserMapper;import io.springboot.sms.core.SmsClient;import lombok.AllArgsConstructor;import lombok.extern.slf4j.Slf4j;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Service;import java.util.List;import java.util.concurrent.TimeUnit;/** * @author wildwind * @date 2022/3/14 * <p> * 手机登录相关业务实现 */@Slf4j@Service@AllArgsConstructorpublic class AppServiceImpl implements AppService { private final RedisTemplate redisTemplate; private final SysUserMapper userMapper; private final SmsClient smsClient; /** * 发送手机验证码 : 调用短信网关发送验证码,测试返回前端 * @param phone 手机号 * @return code */ @Override public R<Boolean> sendSmsCode(String phone) { List<SysUser> userList = userMapper.selectList(Wrappers.<SysUser>query().lambda().eq(SysUser::getPhone, phone)); if (CollUtil.isEmpty(userList)) { log.info("手机号未注册:{}", phone); return R.ok(Boolean.FALSE, "手机号未注册"); } Object codeObj = redisTemplate.opsForValue().get(CacheConstants.DEFAULT_CODE_KEY + phone); if (codeObj != null) { log.info("手机号验证码未过期:{},{}", phone, codeObj); return R.ok(Boolean.FALSE, "验证码发送过频繁"); } String code = RandomUtil.randomNumbers(Integer.parseInt(SecurityConstants.CODE_SIZE)); log.info("手机号生成验证码成功:{},{}", phone, code); redisTemplate.opsForValue().set(CacheConstants.DEFAULT_CODE_KEY + phone, code, SecurityConstants.CODE_TIME, TimeUnit.SECONDS); // 调用短信通道发送// this.smsClient.sendCode(code, phone); return R.ok(Boolean.TRUE, code); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.iam.service.impl;import cn.hutool.core.collection.CollUtil;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.strongdata.dataflow.iam.api.entity.SysDept;import com.strongdata.dataflow.iam.api.entity.SysDeptRelation;import cn.chinatowercom.dataflow.iam.mapper.SysDeptRelationMapper;import cn.chinatowercom.dataflow.iam.service.SysDeptRelationService;import lombok.RequiredArgsConstructor;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import java.util.List;import java.util.stream.Collectors;/** * <p> * 服务实现类 * </p> * * @author wildwind * @since 2019/2/1 */@Service@RequiredArgsConstructorpublic class SysDeptRelationServiceImpl extends ServiceImpl<SysDeptRelationMapper, SysDeptRelation> implements SysDeptRelationService { private final SysDeptRelationMapper sysDeptRelationMapper; /** * 维护部门关系 * @param sysDept 部门 */ @Override @Transactional(rollbackFor = Exception.class) public void saveDeptRelation(SysDept sysDept) { // 增加部门关系表 List<SysDeptRelation> relationList = sysDeptRelationMapper.selectList( Wrappers.<SysDeptRelation>query().lambda().eq(SysDeptRelation::getDescendant, sysDept.getParentId())) .stream().map(relation -> { relation.setDescendant(sysDept.getDeptId()); return relation; }).collect(Collectors.toList()); if (CollUtil.isNotEmpty(relationList)) { this.saveBatch(relationList); } // 自己也要维护到关系表中 SysDeptRelation own = new SysDeptRelation(); own.setDescendant(sysDept.getDeptId()); own.setAncestor(sysDept.getDeptId()); sysDeptRelationMapper.insert(own); } /** * 通过ID删除部门关系 * @param id */ @Override public void removeDeptRelationById(Long id) { baseMapper.deleteDeptRelationsById(id); } /** * 更新部门关系 * @param relation */ @Override @Transactional(rollbackFor = Exception.class) public void updateDeptRelation(SysDeptRelation relation) { baseMapper.deleteDeptRelations(relation); baseMapper.insertDeptRelations(relation); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.iam.service.impl;import cn.chinatowercom.dataflow.iam.service.SysDeptService;import cn.hutool.core.collection.CollUtil;import cn.hutool.core.lang.tree.Tree;import cn.hutool.core.lang.tree.TreeNode;import cn.hutool.core.lang.tree.TreeUtil;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.strongdata.dataflow.core.security.util.SecurityUtils;import com.strongdata.dataflow.iam.api.entity.SysDept;import com.strongdata.dataflow.iam.api.entity.SysDeptRelation;import cn.chinatowercom.dataflow.iam.mapper.SysDeptMapper;import cn.chinatowercom.dataflow.iam.service.SysDeptRelationService;import lombok.RequiredArgsConstructor;import org.springframework.beans.BeanUtils;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import java.util.*;import java.util.stream.Collectors;/** * <p> * 部门管理 服务实现类 * </p> * * @author wildwind * @since 2022/3/1 */@Service@RequiredArgsConstructorpublic class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService { private final SysDeptRelationService sysDeptRelationService; /** * 添加信息部门 * @param dept 部门 * @return */ @Override @Transactional(rollbackFor = Exception.class) public Boolean saveDept(SysDept dept) { SysDept sysDept = new SysDept(); BeanUtils.copyProperties(dept, sysDept); this.save(sysDept); sysDeptRelationService.saveDeptRelation(sysDept); return Boolean.TRUE; } /** * 删除部门 * @param id 部门 ID * @return 成功、失败 */ @Override @Transactional(rollbackFor = Exception.class) public Boolean removeDeptById(Long id) { // 级联删除部门 List<Long> idList = sysDeptRelationService .list(Wrappers.<SysDeptRelation>query().lambda().eq(SysDeptRelation::getAncestor, id)).stream() .map(SysDeptRelation::getDescendant).collect(Collectors.toList()); if (CollUtil.isNotEmpty(idList)) { this.removeByIds(idList); } // 删除部门级联关系 sysDeptRelationService.removeDeptRelationById(id); return Boolean.TRUE; } /** * 更新部门 * @param sysDept 部门信息 * @return 成功、失败 */ @Override @Transactional(rollbackFor = Exception.class) public Boolean updateDeptById(SysDept sysDept) { // 更新部门状态 this.updateById(sysDept); // 更新部门关系 SysDeptRelation relation = new SysDeptRelation(); relation.setAncestor(sysDept.getParentId()); relation.setDescendant(sysDept.getDeptId()); sysDeptRelationService.updateDeptRelation(relation); return Boolean.TRUE; } @Override public List<Long> listChildDeptId(Long deptId) { List<SysDeptRelation> deptRelations = sysDeptRelationService.list(Wrappers.<SysDeptRelation>lambdaQuery() .eq(SysDeptRelation::getAncestor, deptId).ne(SysDeptRelation::getDescendant, deptId)); if (CollUtil.isNotEmpty(deptRelations)) { return deptRelations.stream().map(SysDeptRelation::getDescendant).collect(Collectors.toList()); } return new ArrayList<>(); } /** * 查询全部部门树 * @return 树 */ @Override public List<Tree<Long>> listDeptTrees() { return getDeptTree(this.list(Wrappers.emptyWrapper())); } /** * 查询用户部门树 * @return */ @Override public List<Tree<Long>> listCurrentUserDeptTrees() { Long deptId = SecurityUtils.getUser().getDeptId(); List<Long> descendantIdList = sysDeptRelationService .list(Wrappers.<SysDeptRelation>query().lambda().eq(SysDeptRelation::getAncestor, deptId)).stream() .map(SysDeptRelation::getDescendant).collect(Collectors.toList()); List<SysDept> deptList = baseMapper.selectBatchIds(descendantIdList); return getDeptTree(deptList); } /** * 构建部门树 * @param depts 部门 * @return */ private List<Tree<Long>> getDeptTree(List<SysDept> depts) { List<TreeNode<Long>> collect = depts.stream().filter(dept -> dept.getDeptId().intValue() != dept.getParentId()) .sorted(Comparator.comparingInt(SysDept::getSortOrder)).map(dept -> { TreeNode<Long> treeNode = new TreeNode(); treeNode.setId(dept.getDeptId()); treeNode.setParentId(dept.getParentId()); treeNode.setName(dept.getName()); treeNode.setWeight(dept.getSortOrder()); // 扩展属性 Map<String, Object> extra = new HashMap<>(4); extra.put("createTime", dept.getCreateTime()); treeNode.setExtra(extra); return treeNode; }).collect(Collectors.toList()); return TreeUtil.build(collect, 0L); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.iam.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.strongdata.dataflow.core.base.constant.CacheConstants;import com.strongdata.dataflow.core.base.constant.enums.DictTypeEnum;import com.strongdata.dataflow.iam.api.entity.SysDict;import com.strongdata.dataflow.iam.api.entity.SysDictItem;import cn.chinatowercom.dataflow.iam.mapper.SysDictItemMapper;import cn.chinatowercom.dataflow.iam.service.SysDictItemService;import cn.chinatowercom.dataflow.iam.service.SysDictService;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.iam.service.impl;import cn.chinatowercom.dataflow.iam.service.SysDictService;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.strongdata.dataflow.core.base.constant.CacheConstants;import com.strongdata.dataflow.core.base.constant.enums.DictTypeEnum;import com.strongdata.dataflow.iam.api.entity.SysDict;import com.strongdata.dataflow.iam.api.entity.SysDictItem;import cn.chinatowercom.dataflow.iam.mapper.SysDictItemMapper;import cn.chinatowercom.dataflow.iam.mapper.SysDictMapper;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;/** * 字典表 * * @author wildwind * @date 2022/03/19 */@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); // 系统内置 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()); // 系统内置 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.iam.service.impl;import cn.chinatowercom.dataflow.iam.mapper.SysFileMapper;import cn.chinatowercom.dataflow.iam.service.SysFileService;import cn.hutool.core.io.FileUtil;import cn.hutool.core.io.IoUtil;import cn.hutool.core.text.StrPool;import cn.hutool.core.util.IdUtil;import com.amazonaws.services.s3.model.S3Object;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.iam.api.entity.SysFile;import com.strongdata.rill.oss.config.OssProperties;import com.strongdata.rill.oss.service.OssTemplate;import lombok.AllArgsConstructor;import lombok.SneakyThrows;import lombok.extern.slf4j.Slf4j;import org.springframework.transaction.annotation.Transactional;import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;import java.util.HashMap;import java.util.Map;/** * 文件管理 * * @author wildwind * @date 2022-03-18 */@Slf4j//@Service@AllArgsConstructorpublic class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFile> implements SysFileService { private final OssProperties ossProperties; private final OssTemplate ossTemplate; /** * 上传文件 * @param file * @return */ @Override public R uploadFile(MultipartFile file) { String fileName = IdUtil.simpleUUID() + StrPool.DOT + FileUtil.extName(file.getOriginalFilename()); Map<String, String> resultMap = new HashMap<>(4); resultMap.put("bucketName", ossProperties.getBucketName()); resultMap.put("fileName", fileName); resultMap.put("url", String.format("/admin/sys-file/%s/%s", ossProperties.getBucketName(), fileName)); try { ossTemplate.putObject(ossProperties.getBucketName(), fileName, file.getContentType(), file.getInputStream()); // 文件管理数据记录,收集管理追踪文件 fileLog(file, fileName); } catch (Exception e) { log.error("上传失败", e); return R.failed(e.getLocalizedMessage()); } return R.ok(resultMap); } /** * 读取文件 * @param bucket * @param fileName * @param response */ @Override public void getFile(String bucket, String fileName, HttpServletResponse response) { try (S3Object s3Object = ossTemplate.getObject(bucket, fileName)) { response.setContentType("application/octet-stream; charset=UTF-8"); IoUtil.copy(s3Object.getObjectContent(), response.getOutputStream()); } catch (Exception e) { log.error("文件读取异常: {}", e.getLocalizedMessage()); } } /** * 删除文件 * @param id * @return */ @Override @SneakyThrows @Transactional(rollbackFor = Exception.class) public Boolean deleteFile(Long id) { SysFile file = this.getById(id); ossTemplate.removeObject(ossProperties.getBucketName(), file.getFileName()); return this.removeById(id); } /** * 文件管理数据记录,收集管理追踪文件 * @param file 上传文件格式 * @param fileName 文件名 */ private void fileLog(MultipartFile file, String fileName) { SysFile sysFile = new SysFile(); sysFile.setFileName(fileName); sysFile.setOriginal(file.getOriginalFilename()); sysFile.setFileSize(file.getSize()); sysFile.setType(FileUtil.extName(file.getOriginalFilename())); sysFile.setBucketName(ossProperties.getBucketName()); this.save(sysFile); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.iam.service.impl;import cn.chinatowercom.dataflow.iam.mapper.SysLogMapper;import cn.chinatowercom.dataflow.iam.service.SysLogService;import cn.hutool.core.text.CharSequenceUtil;import cn.hutool.core.util.ArrayUtil;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;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.iam.api.dto.SysLogDTO;import com.strongdata.dataflow.iam.api.entity.SysLog;import org.springframework.stereotype.Service;import java.util.List;/** * <p> * 日志表 服务实现类 * </p> * * @author wildwind * @since 2022/2/1 */@Servicepublic class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> implements SysLogService { @Override public Page getLogByPage(Page page, SysLogDTO sysLog) { return baseMapper.selectPage(page, buildQueryWrapper(sysLog)); } /** * 列表查询日志 * @param sysLog 查询条件 * @return List */ @Override public List getLogList(SysLogDTO sysLog) { return baseMapper.selectList(buildQueryWrapper(sysLog)); } /** * 构建查询的 wrapper * @param sysLog 查询条件 * @return LambdaQueryWrapper */ private LambdaQueryWrapper buildQueryWrapper(SysLogDTO sysLog) { LambdaQueryWrapper<SysLog> wrapper = Wrappers.lambdaQuery(); if (CharSequenceUtil.isNotBlank(sysLog.getType())) { wrapper.eq(SysLog::getType, sysLog.getType()); } if (ArrayUtil.isNotEmpty(sysLog.getCreateTime())) { wrapper.ge(SysLog::getCreateTime, sysLog.getCreateTime()[0]).le(SysLog::getCreateTime, sysLog.getCreateTime()[1]); } return wrapper; }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.iam.service.impl;import cn.chinatowercom.dataflow.iam.mapper.SysMenuMapper;import cn.chinatowercom.dataflow.iam.mapper.SysRoleMenuMapper;import cn.chinatowercom.dataflow.iam.service.SysMenuService;import cn.hutool.core.collection.CollUtil;import cn.hutool.core.lang.tree.Tree;import cn.hutool.core.lang.tree.TreeNode;import cn.hutool.core.lang.tree.TreeUtil;import cn.hutool.core.text.CharSequenceUtil;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.strongdata.dataflow.core.base.constant.CacheConstants;import com.strongdata.dataflow.core.base.constant.CommonConstants;import com.strongdata.dataflow.core.base.constant.enums.MenuTypeEnum;import com.strongdata.dataflow.iam.api.entity.SysMenu;import com.strongdata.dataflow.iam.api.entity.SysRoleMenu;import lombok.RequiredArgsConstructor;import org.springframework.cache.annotation.CacheEvict;import org.springframework.cache.annotation.Cacheable;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import org.springframework.util.Assert;import javax.validation.constraints.NotNull;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Set;import java.util.function.Function;import java.util.stream.Collectors;/** * <p> * 菜单权限表 服务实现类 * </p> * * @author wildwind * @since 2022-03-29 */@Service@RequiredArgsConstructorpublic class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService { private final SysRoleMenuMapper sysRoleMenuMapper; @Override @Cacheable(value = CacheConstants.MENU_DETAILS, key = "#roleId + '_menu'", unless = "#result == null") public Set<SysMenu> findMenuByRoleId(Long roleId) { return baseMapper.listMenusByRoleId(roleId); } /** * 级联删除菜单 * @param id 菜单ID * @return true成功, false失败 */ @Override @Transactional(rollbackFor = Exception.class) @CacheEvict(value = CacheConstants.MENU_DETAILS, allEntries = true) public Boolean removeMenuById(Long id) { // 查询父节点为当前节点的节点 List<SysMenu> menuList = this.list(Wrappers.<SysMenu>query().lambda().eq(SysMenu::getParentId, id)); Assert.isTrue(CollUtil.isEmpty(menuList), "菜单含有下级不能删除"); sysRoleMenuMapper.delete(Wrappers.<SysRoleMenu>query().lambda().eq(SysRoleMenu::getMenuId, id)); // 删除当前菜单及其子菜单 return this.removeById(id); } @Override @CacheEvict(value = CacheConstants.MENU_DETAILS, allEntries = true) public Boolean updateMenuById(SysMenu sysMenu) { return this.updateById(sysMenu); } /** * 构建树查询 1. 不是懒加载情况,查询全部 2. 是懒加载,根据parentId 查询 2.1 父节点为空,则查询ID -1 * @param lazy 是否是懒加载 * @param parentId 父节点ID * @return */ @Override public List<Tree<Long>> treeMenu(boolean lazy, Long parentId) { if (!lazy) { List<TreeNode<Long>> collect = baseMapper .selectList(Wrappers.<SysMenu>lambdaQuery().orderByAsc(SysMenu::getSortOrder)).stream() .map(getNodeFunction()).collect(Collectors.toList()); return TreeUtil.build(collect, CommonConstants.MENU_TREE_ROOT_ID); } Long parent = parentId == null ? CommonConstants.MENU_TREE_ROOT_ID : parentId; List<TreeNode<Long>> collect = baseMapper .selectList(Wrappers.<SysMenu>lambdaQuery().eq(SysMenu::getParentId, parent) .orderByAsc(SysMenu::getSortOrder)) .stream().map(getNodeFunction()).collect(Collectors.toList()); return TreeUtil.build(collect, parent); } /** * 查询菜单 * @param all 全部菜单 * @param parentId 父节点ID * @return */ @Override public List<Tree<Long>> filterMenu(Set<SysMenu> all, Long parentId) { List<TreeNode<Long>> collect = all.stream() .filter(menu -> MenuTypeEnum.LEFT_MENU.getType().equals(menu.getType())) .filter(menu -> CharSequenceUtil.isNotBlank(menu.getPath())).map(getNodeFunction()).collect(Collectors.toList()); Long parent = parentId == null ? CommonConstants.MENU_TREE_ROOT_ID : parentId; return TreeUtil.build(collect, parent); } /* 清除菜单缓存接口 */ @Override @CacheEvict(value = CacheConstants.MENU_DETAILS, allEntries = true) public void clearMenuCache() { // Do nothing because of X and Y. } @NotNull private Function<SysMenu, TreeNode<Long>> getNodeFunction() { return menu -> { TreeNode<Long> node = new TreeNode<>(); node.setId(menu.getMenuId()); node.setName(menu.getName()); node.setParentId(menu.getParentId()); node.setWeight(menu.getSortOrder()); // 扩展属性 Map<String, Object> extra = new HashMap<>(); extra.put("icon", menu.getIcon()); extra.put("path", menu.getPath()); extra.put("type", menu.getType()); extra.put("permission", menu.getPermission()); extra.put("label", menu.getName()); extra.put("sortOrder", menu.getSortOrder()); extra.put("keepAlive", menu.getKeepAlive()); extra.put("component", menu.getComponent()); node.setExtra(extra); return node; }; }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.iam.service.impl;import cn.chinatowercom.dataflow.iam.service.SysOauthClientDetailsService;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.strongdata.dataflow.core.base.constant.CacheConstants;import com.strongdata.dataflow.iam.api.entity.SysOauthClientDetails;import cn.chinatowercom.dataflow.iam.mapper.SysOauthClientDetailsMapper;import org.springframework.cache.annotation.CacheEvict;import org.springframework.stereotype.Service;/** * <p> * 服务实现类 * </p> * * @author wildwind * @since 2022/2/1 */@Servicepublic class SysOauthClientDetailsServiceImpl extends ServiceImpl<SysOauthClientDetailsMapper, SysOauthClientDetails> implements SysOauthClientDetailsService { /** * 通过ID删除客户端 * @param id * @return */ @Override @CacheEvict(value = CacheConstants.CLIENT_DETAILS_KEY, key = "#id") public Boolean removeClientDetailsById(String id) { return this.removeById(id); } /** * 根据客户端信息 * @param clientDetails * @return */ @Override @CacheEvict(value = CacheConstants.CLIENT_DETAILS_KEY, key = "#clientDetails.clientId") public Boolean updateClientDetailsById(SysOauthClientDetails clientDetails) { return this.updateById(clientDetails); } /** * 清除客户端缓存 */ @Override @CacheEvict(value = CacheConstants.CLIENT_DETAILS_KEY, allEntries = true) public void clearClientCache() { // Do nothing because of X and Y. }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.iam.service.impl;import cn.chinatowercom.dataflow.iam.mapper.SysRoleMenuMapper;import cn.chinatowercom.dataflow.iam.service.SysRoleMenuService;import cn.hutool.core.text.CharSequenceUtil;import cn.hutool.core.text.StrPool;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.strongdata.dataflow.core.base.constant.CacheConstants;import com.strongdata.dataflow.iam.api.entity.SysRoleMenu;import lombok.RequiredArgsConstructor;import org.springframework.cache.CacheManager;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import java.util.Arrays;import java.util.List;import java.util.Objects;import java.util.stream.Collectors;/** * <p> * 角色菜单表 服务实现类 * </p> * * @author wildwind * @since 2022/2/1 */@Service@RequiredArgsConstructorpublic class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService { private final CacheManager cacheManager; /** * @param role * @param roleId 角色 * @param menuIds 菜单ID拼成的字符串,每个id之间根据逗号分隔 * @return */ @Override @Transactional(rollbackFor = Exception.class) public Boolean saveRoleMenus(String role, Long roleId, String menuIds) { this.remove(Wrappers.<SysRoleMenu>query().lambda().eq(SysRoleMenu::getRoleId, roleId)); if (CharSequenceUtil.isBlank(menuIds)) { return Boolean.TRUE; } List<SysRoleMenu> roleMenuList = Arrays.stream(menuIds.split(StrPool.COMMA)).map(menuId -> { SysRoleMenu roleMenu = new SysRoleMenu(); roleMenu.setRoleId(roleId); roleMenu.setMenuId(Long.valueOf(menuId)); return roleMenu; }).collect(Collectors.toList()); // 清空userinfo Objects.requireNonNull(cacheManager.getCache(CacheConstants.USER_DETAILS)).clear(); // 清空全部的菜单缓存 Objects.requireNonNull(cacheManager.getCache(CacheConstants.MENU_DETAILS)).clear(); return this.saveBatch(roleMenuList); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.iam.service.impl;import cn.chinatowercom.dataflow.iam.service.SysRoleService;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.strongdata.dataflow.core.base.constant.CacheConstants;import com.strongdata.dataflow.iam.api.entity.SysRole;import com.strongdata.dataflow.iam.api.entity.SysRoleMenu;import cn.chinatowercom.dataflow.iam.mapper.SysRoleMapper;import cn.chinatowercom.dataflow.iam.mapper.SysRoleMenuMapper;import lombok.RequiredArgsConstructor;import org.springframework.cache.annotation.CacheEvict;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;/** * <p> * 服务实现类 * </p> * * @author wildwind * @since 2022/2/1 */@Service@RequiredArgsConstructorpublic class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService { private final SysRoleMenuMapper sysRoleMenuMapper; /** * 通过角色ID,删除角色,并清空角色菜单缓存 * @param id * @return */ @Override @Transactional(rollbackFor = Exception.class) @CacheEvict(value = CacheConstants.MENU_DETAILS, allEntries = true) public Boolean removeRoleById(Long id) { sysRoleMenuMapper.delete(Wrappers.<SysRoleMenu>update().lambda().eq(SysRoleMenu::getRoleId, id)); return this.removeById(id); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.iam.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.strongdata.dataflow.iam.api.entity.SysUserRole;import cn.chinatowercom.dataflow.iam.mapper.SysUserRoleMapper;import cn.chinatowercom.dataflow.iam.service.SysUserRoleService;import org.springframework.stereotype.Service;/** * <p> * 用户角色表 服务实现类 * </p> * * @author widlwind * @since 2022/2/1 */@Servicepublic class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.iam.service.impl;import cn.chinatowercom.dataflow.iam.mapper.SysDeptMapper;import cn.chinatowercom.dataflow.iam.mapper.SysRoleMapper;import cn.chinatowercom.dataflow.iam.mapper.SysUserMapper;import cn.chinatowercom.dataflow.iam.mapper.SysUserRoleMapper;import cn.chinatowercom.dataflow.iam.service.SysMenuService;import cn.chinatowercom.dataflow.iam.service.SysUserService;import cn.hutool.core.collection.CollUtil;import cn.hutool.core.text.CharSequenceUtil;import cn.hutool.core.text.StrPool;import cn.hutool.core.util.ArrayUtil;import cn.hutool.core.util.StrUtil;import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;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.constant.CacheConstants;import com.strongdata.dataflow.core.base.constant.CommonConstants;import com.strongdata.dataflow.core.base.constant.enums.MenuTypeEnum;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.iam.api.dto.UserDTO;import com.strongdata.dataflow.iam.api.dto.UserInfo;import com.strongdata.dataflow.iam.api.entity.*;import com.strongdata.dataflow.iam.api.vo.UserExcelVO;import com.strongdata.dataflow.iam.api.vo.UserVO;import com.strongdata.rill.plus.excel.ExcelErrorMessage;import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.BeanUtils;import org.springframework.cache.annotation.CacheEvict;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import org.springframework.util.Assert;import org.springframework.validation.BindingResult;import java.time.LocalDateTime;import java.util.*;import java.util.stream.Collectors;/** * @author wildwind * @date 2022/2/1 */@Slf4j@Service@RequiredArgsConstructorpublic class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService { private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder(); private final SysRoleMapper sysRoleMapper; private final SysDeptMapper sysDeptMapper; private final SysMenuService sysMenuService; private final SysUserRoleMapper sysUserRoleMapper; /** * 保存用户信息 * @param userDto DTO 对象 * @return success/fail */ @Override @Transactional(rollbackFor = Exception.class) public Boolean saveUser(UserDTO userDto) { SysUser sysUser = new SysUser(); BeanUtils.copyProperties(userDto, sysUser); sysUser.setDelFlag(CommonConstants.STATUS_NORMAL); sysUser.setPassword(ENCODER.encode(userDto.getPassword())); baseMapper.insert(sysUser); userDto.getRole().stream().map(roleId -> { SysUserRole userRole = new SysUserRole(); userRole.setUserId(sysUser.getUserId()); userRole.setRoleId(roleId); return userRole; }).forEach(sysUserRoleMapper::insert); return Boolean.TRUE; } /** * 通过查用户的全部信息 * @param sysUser 用户 * @return */ @Override public UserInfo getUserInfo(SysUser sysUser) { UserInfo userInfo = new UserInfo(); userInfo.setSysUser(sysUser); // 设置角色列表 List<SysRole> roleList = sysRoleMapper.listRolesByUserId(sysUser.getUserId()); userInfo.setRoleList(roleList); // 设置角色列表 (ID) List<Long> roleIds = roleList.stream().map(SysRole::getRoleId).collect(Collectors.toList()); userInfo.setRoles(ArrayUtil.toArray(roleIds, Long.class)); // 设置权限列表(menu.permission) Set<String> permissions = roleIds.stream().map(sysMenuService::findMenuByRoleId).flatMap(Collection::stream) .filter(m -> MenuTypeEnum.BUTTON.getType().equals(m.getType())).map(SysMenu::getPermission) .filter(StrUtil::isNotBlank).collect(Collectors.toSet()); userInfo.setPermissions(ArrayUtil.toArray(permissions, String.class)); return userInfo; } /** * 分页查询用户信息(含有角色信息) * @param page 分页对象 * @param userDTO 参数列表 * @return */ @Override public IPage<List<UserVO>> getUserWithRolePage(Page page, UserDTO userDTO) { return baseMapper.getUserVosPage(page, userDTO); } /** * 通过ID查询用户信息 * @param id 用户ID * @return 用户信息 */ @Override public UserVO getUserVoById(Long id) { return baseMapper.getUserVoById(id); } /** * 通过手机号查询用户信息 * @param phone 用户手机号 * @return 用户信息 */ @Override public UserVO getUserVoByPhone(String phone) { return baseMapper.getUserVoByPhone(phone); } /** * 删除用户 * @param sysUser 用户 * @return Boolean */ @Override @CacheEvict(value = CacheConstants.USER_DETAILS, key = "#sysUser.username") public Boolean removeUserById(SysUser sysUser) { sysUserRoleMapper.deleteByUserId(sysUser.getUserId()); this.removeById(sysUser.getUserId()); return Boolean.TRUE; } /** * @desc 逻辑删除用户信息 * @author suichuanguo * @time 2022/6/17 10:20 * @param * @return */ @CacheEvict(value = CacheConstants.USER_DETAILS, key = "#sysUser.username") public Boolean removeUserByLogic(SysUser sysUser) { UpdateWrapper<SysUser> wrapper= new UpdateWrapper(); wrapper.eq("user_id",sysUser.getUserId()); wrapper.set("del_flag",sysUser.getDelFlag()); baseMapper.update(null,wrapper); return Boolean.TRUE; } @Override @CacheEvict(value = CacheConstants.USER_DETAILS, key = "#userDto.username") public Boolean updateUserInfo(UserDTO userDto) { UserVO userVO = baseMapper.getUserVoByUsername(userDto.getUsername()); Assert.isTrue(ENCODER.matches(userDto.getPassword(), userVO.getPassword()), "原密码错误,修改失败"); SysUser sysUser = new SysUser(); if (CharSequenceUtil.isNotBlank(userDto.getNewpassword1())) { sysUser.setPassword(ENCODER.encode(userDto.getNewpassword1())); } sysUser.setPhone(userDto.getPhone()); sysUser.setUserId(userVO.getUserId()); sysUser.setAvatar(userDto.getAvatar()); return this.updateById(sysUser); } @Override @Transactional(rollbackFor = Exception.class) @CacheEvict(value = CacheConstants.USER_DETAILS, key = "#userDto.username") public Boolean updateUser(UserDTO userDto) { SysUser sysUser = new SysUser(); BeanUtils.copyProperties(userDto, sysUser); sysUser.setUpdateTime(LocalDateTime.now()); if (CharSequenceUtil.isNotBlank(userDto.getPassword())) { sysUser.setPassword(ENCODER.encode(userDto.getPassword())); } this.updateById(sysUser); sysUserRoleMapper .delete(Wrappers.<SysUserRole>update().lambda().eq(SysUserRole::getUserId, userDto.getUserId())); userDto.getRole().forEach(roleId -> { SysUserRole userRole = new SysUserRole(); userRole.setUserId(sysUser.getUserId()); userRole.setRoleId(roleId); userRole.insert(); }); return Boolean.TRUE; } /** * 查询上级部门的用户信息 * @param username 用户名 * @return R */ @Override public List<SysUser> listAncestorUsersByUsername(String username) { SysUser sysUser = this.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, username)); SysDept sysDept = sysDeptMapper.selectById(sysUser.getDeptId()); if (sysDept == null) { return Collections.emptyList(); } Long parentId = sysDept.getParentId(); return this.list(Wrappers.<SysUser>query().lambda().eq(SysUser::getDeptId, parentId)); } /** * 查询全部的用户 * @param userDTO 查询条件 * @return list */ @Override public List<UserExcelVO> listUser(UserDTO userDTO) { List<UserVO> voList = baseMapper.selectVoList(userDTO); // 转换成execl 对象输出 List<UserExcelVO> userExcelVOList = voList.stream().map(userVO -> { UserExcelVO excelVO = new UserExcelVO(); BeanUtils.copyProperties(userVO, excelVO); String roleNameList = userVO.getRoleList().stream().map(SysRole::getRoleName) .collect(Collectors.joining(StrPool.COMMA)); excelVO.setRoleNameList(roleNameList); return excelVO; }).collect(Collectors.toList()); return userExcelVOList; } /** * excel 导入用户, 插入正确的 错误的提示行号 * @param excelVOList excel 列表数据 * @param bindingResult 错误数据 * @return ok fail */ @Override public R importUser(List<UserExcelVO> excelVOList, BindingResult bindingResult) { // 通用校验获取失败的数据 List<ExcelErrorMessage> errorMessageList = (List<ExcelErrorMessage>) bindingResult.getTarget(); // 个性化校验逻辑 List<SysUser> userList = this.list(); List<SysDept> deptList = sysDeptMapper.selectList(Wrappers.emptyWrapper()); List<SysRole> roleList = sysRoleMapper.selectList(Wrappers.emptyWrapper()); // 执行数据插入操作 组装 UserDto for (int i = 0; i < excelVOList.size(); i++) { UserExcelVO excel = excelVOList.get(i); Set<String> errorMsg = new HashSet<>(); // 校验用户名是否存在 boolean exsitUserName = userList.stream() .anyMatch(sysUser -> excel.getUsername().equals(sysUser.getUsername())); if (exsitUserName) { errorMsg.add(String.format("%s 用户名已存在", excel.getUsername())); } // 判断输入的部门名称列表是否合法 Optional<SysDept> deptOptional = deptList.stream() .filter(dept -> excel.getDeptName().equals(dept.getName())).findFirst(); if (!deptOptional.isPresent()) { errorMsg.add(String.format("%s 部门名称不存在", excel.getDeptName())); } // 判断输入的角色名称列表是否合法 List<String> roleNameList = CharSequenceUtil.split(excel.getRoleNameList(), StrPool.COMMA); List<SysRole> roleCollList = roleList.stream() .filter(role -> roleNameList.stream().anyMatch(name -> role.getRoleName().equals(name))) .collect(Collectors.toList()); if (roleCollList.size() != roleNameList.size()) { errorMsg.add(String.format("%s 角色名称不存在", excel.getRoleNameList())); } // 数据合法情况 if (CollUtil.isEmpty(errorMsg)) { insertExcelUser(excel, deptOptional, roleCollList); } else { // 数据不合法情况 errorMessageList.add(new ExcelErrorMessage((long) (i + 2), errorMsg)); } } if (CollUtil.isNotEmpty(errorMessageList)) { return R.failed(errorMessageList); } return R.ok(); } @Override public List<Long> listUserIdByDeptIds(Set<Long> deptIds) { return this.listObjs( Wrappers.lambdaQuery(SysUser.class).select(SysUser::getUserId).in(SysUser::getDeptId, deptIds), Long.class::cast); } /** * 插入excel User */ private void insertExcelUser(UserExcelVO excel, Optional<SysDept> deptOptional, List<SysRole> roleCollList) { UserDTO userDTO = new UserDTO(); userDTO.setUsername(excel.getUsername()); userDTO.setPhone(excel.getPhone()); // 批量导入初始密码为手机号 userDTO.setPassword(userDTO.getPhone()); // 根据部门名称查询部门ID if(deptOptional.isPresent()) userDTO.setDeptId(deptOptional.get().getDeptId()); // 根据角色名称查询角色ID List<Long> roleIdList = roleCollList.stream().map(SysRole::getRoleId).collect(Collectors.toList()); userDTO.setRole(roleIdList); // 插入用户 this.saveUser(userDTO); }}
package cn.chinatowercom.dataflow.iam.service.impl;import cn.chinatowercom.dataflow.iam.service.WechatEnterpriseService;import com.alibaba.fastjson.JSON;import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.strongdata.dataflow.core.base.constant.CommonConstants;import com.strongdata.dataflow.iam.api.constant.enums.EventChangeTypeEnum;import com.strongdata.dataflow.iam.api.entity.SysUser;import com.strongdata.dataflow.iam.api.entity.SysUserRole;import com.strongdata.dataflow.iam.api.entity.WechatEnterpriseUserInfo;import com.strongdata.dataflow.iam.api.vo.UserVO;import cn.chinatowercom.dataflow.iam.mapper.SysUserMapper;import cn.chinatowercom.dataflow.iam.mapper.SysUserRoleMapper;import cn.chinatowercom.dataflow.iam.mapper.WechatEnterpriseMapper;import cn.chinatowercom.dataflow.iam.service.SysUserService;import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import org.springframework.util.StringUtils;/** * @功能描述:企业微信相关业务 * @作 者:suichuanguo * @创建时间:2022-05-30 10:43 **/@Slf4j@Service@RequiredArgsConstructorpublic class WechatEnterpriseImpl extends ServiceImpl<WechatEnterpriseMapper, WechatEnterpriseUserInfo> implements WechatEnterpriseService { private final SysUserService userService; private final SysUserRoleMapper sysUserRoleMapper; private final SysUserMapper sysUserMapper; private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder(); @Override @Transactional(rollbackFor = Exception.class) public Integer saveThirdUserInfo(WechatEnterpriseUserInfo userInfo) { if(EventChangeTypeEnum.CREATE_USER.getType().equals(userInfo.getChangeType())) createUser(userInfo); if(EventChangeTypeEnum.UPDATE_USER.getType().equals(userInfo.getChangeType())) updateUser(userInfo); if(EventChangeTypeEnum.DELETE_USER.getType().equals(userInfo.getChangeType())) deleteUser(userInfo); return CommonConstants.SUCCESS; } public Integer createUser(WechatEnterpriseUserInfo userInfo){ log.info("创建用户信息:{}", JSON.toJSONString(userInfo)); UserVO userVO = userService.getUserVoByPhone(userInfo.getMobile()); SysUser sysUser = new SysUser(); SysUserRole userRole = new SysUserRole(); if(userVO == null){ sysUser.setUsername(userInfo.getName()); sysUser.setPassword(ENCODER.encode(CommonConstants.DEFAULT_PASSWORD)); sysUser.setPhone(userInfo.getMobile()); sysUser.setAvatar(userInfo.getAvatar()); sysUser.setDelFlag(CommonConstants.STATUS_NORMAL); sysUserMapper.insert(sysUser); userRole.setUserId(sysUser.getUserId()); }else if(userVO.getUserId()>0&&!StringUtils.hasText(userVO.getPhone())){ userRole.setUserId(userVO.getUserId()); }else { return CommonConstants.EXISTS; } userRole.setRoleId(CommonConstants.DEFAULT_ROLE_ID); sysUserRoleMapper.insert(userRole); userInfo.setUserId(userRole.getUserId()); baseMapper.insert(userInfo); return CommonConstants.SUCCESS; } public Integer updateUser(WechatEnterpriseUserInfo userInfo){ log.info("修改用户信息:{}", JSON.toJSONString(userInfo)); WechatEnterpriseUserInfo updUserInfo = baseMapper.selectOne(Wrappers.<WechatEnterpriseUserInfo>query().lambda() .eq(WechatEnterpriseUserInfo::getThirdUserId, userInfo.getThirdUserId()).notIn(WechatEnterpriseUserInfo::getStatus,"5")); if(updUserInfo!=null){ UpdateWrapper<WechatEnterpriseUserInfo> wrapper= new UpdateWrapper(); wrapper.eq("third_user_id",userInfo.getThirdUserId()); baseMapper.update(userInfo,wrapper); SysUser sysUser = new SysUser(); sysUser.setUserId(updUserInfo.getUserId()); sysUser.setUsername(userInfo.getName()); sysUser.setPhone(userInfo.getMobile()); sysUser.setAvatar(userInfo.getAvatar()); if(Integer.valueOf("2").equals(userInfo.getStatus())&&Integer.valueOf("4").equals(userInfo.getStatus())) sysUser.setLockFlag(CommonConstants.STATUS_LOCK); userService.updateById(sysUser); } return CommonConstants.SUCCESS; } public Integer deleteUser(WechatEnterpriseUserInfo userInfo){ log.info("删除用户信息:{}", JSON.toJSONString(userInfo)); WechatEnterpriseUserInfo delUserInfo = baseMapper.selectOne(Wrappers.<WechatEnterpriseUserInfo>query().lambda() .eq(WechatEnterpriseUserInfo::getThirdUserId, userInfo.getThirdUserId()).notIn(WechatEnterpriseUserInfo::getStatus,"5")); if(delUserInfo!=null){ UpdateWrapper<WechatEnterpriseUserInfo> wrapper= new UpdateWrapper(); wrapper.eq("third_user_id",userInfo.getThirdUserId()); wrapper.set("status",userInfo.getStatus()); baseMapper.update(null,wrapper); SysUser sysUser = new SysUser(); sysUser.setUsername(delUserInfo.getName()); sysUser.setUserId(delUserInfo.getUserId()); sysUser.setDelFlag(CommonConstants.STATUS_DEL); userService.removeUserByLogic(sysUser); } return CommonConstants.SUCCESS; }}
package com.strongdata.jsurvey.api.web.controller;import cn.hutool.core.io.FileUtil;import cn.hutool.core.util.CharUtil;import cn.hutool.core.util.IdUtil;import cn.hutool.core.util.StrUtil;import com.strongdata.jsurvey.api.annotation.NotLogin;import com.strongdata.jsurvey.common.util.AsyncProcessUtils;import com.strongdata.jsurvey.common.util.Result;import com.strongdata.jsurvey.storage.cloud.OssStorageFactory;import org.springframework.web.bind.annotation.*;import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;import java.io.IOException;/** * * @description : 通用 * @create : 2022/06/08 15:32 **/@RestController@RequestMapping("/common/")public class CommonController { /** * 获取异步处理进度 */ @GetMapping("/process") public Result getProcess(@RequestParam String key) { return Result.success(AsyncProcessUtils.getProcess(key)); } /** * 上传 * * @param file * @return * @throws IOException */ @PostMapping("/upload") @NotLogin public Result avatar(@RequestParam("file") MultipartFile file) throws IOException { if (!file.isEmpty()) { String path = new StringBuffer(IdUtil.simpleUUID()) .append(CharUtil.DOT) .append(FileUtil.extName(file.getOriginalFilename())).toString(); String url = OssStorageFactory.getStorageService().upload(file.getInputStream(), path); return Result.success(url); } return Result.failed("上传文件异常,请联系管理员"); } /** * 下载 * * @param id * @return * @throws IOException */ @GetMapping("/download/{id}") @NotLogin public void download(HttpServletResponse response, @PathVariable("id") String id){ if (!StrUtil.isBlank(id)) { OssStorageFactory.getStorageService().download(id, response); } }}
package com.strongdata.jsurvey.api.web.controller;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.strongdata.jsurvey.common.util.CacheUtils;import com.strongdata.jsurvey.common.util.Result;import com.strongdata.jsurvey.form.entity.UserFormDataEntity;import com.strongdata.jsurvey.form.service.FormDashboardService;import com.strongdata.jsurvey.form.service.UserFormDataService;import com.strongdata.jsurvey.form.service.UserFormViewCountService;import com.strongdata.jsurvey.form.util.FormAuthUtils;import lombok.RequiredArgsConstructor;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import java.util.Map;/** * 表单报表 * * * @description : 报表相关接口 * @create : 2022/12/30 16:47 **/@RestController@RequiredArgsConstructorpublic class FormDashboardController { private final CacheUtils cacheUtils; private final UserFormViewCountService userFormViewCountService; private final UserFormDataService userFormDataService; private final FormDashboardService formDashboardService; /** * 表单收集信息 */ @GetMapping("/user/form/report/stats") public Result formReportStats(String formKey) { //浏览量 Long viewCount = userFormViewCountService.count(formKey); //平均完成时间 Map<String, Object> resultMap = userFormDataService.getMap(Wrappers.<UserFormDataEntity>query().select("AVG(complete_time) as avgCompleteTime, count(1) as completeCount").eq("form_key", formKey)); resultMap.put("viewCount", viewCount); return Result.success(resultMap); } /** * 表单收集情况按周查看 */ @GetMapping("/user/form/report/situation") public Result formReportSituation(String formKey) { FormAuthUtils.hasPermission(formKey); return Result.success(formDashboardService.formReportSituation(formKey)); } /** * 项目收集位置情况 */ @GetMapping("/user/form/report/position") public Result formReportPosition(String formKey) { FormAuthUtils.hasPermission(formKey); return Result.success(formDashboardService.formReportPosition(formKey)); } /** * 项目收集设备 */ @GetMapping("/user/form/report/device") public Result formReportDevice(String formKey) { FormAuthUtils.hasPermission(formKey); return Result.success(formDashboardService.formReportDevice(formKey)); } /** * 项目收集来源 */ @GetMapping("/user/form/report/source") public Result formReportSource(String formKey) { FormAuthUtils.hasPermission(formKey); return Result.success(formDashboardService.formReportSource(formKey)); } /** * 数据分析 */ @GetMapping("/user/form/report/analysis") public Result formReportAnalysis(String formKey) { FormAuthUtils.hasPermission(formKey); return Result.success(formDashboardService.formReportAnalysis(formKey)); }}
package com.strongdata.jsurvey.api.web.controller;import cn.hutool.core.util.ObjectUtil;import cn.hutool.core.util.StrUtil;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.jsurvey.common.util.QueryWrapperUtils;import com.strongdata.jsurvey.common.util.Result;import com.strongdata.jsurvey.form.entity.FormTemplateCategoryEntity;import com.strongdata.jsurvey.form.entity.FormTemplateEntity;import com.strongdata.jsurvey.form.request.QueryFormTemplateRequest;import com.strongdata.jsurvey.form.request.QueryFormTemplateTypeRequest;import com.strongdata.jsurvey.form.service.*;import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;import org.springframework.web.bind.annotation.*;import javax.validation.constraints.NotBlank;import java.util.List;/** * 表单模板 * * * @description : 表单模板接口 * @create : 2022/01/06 10:54 **/@Slf4j@RestController@RequiredArgsConstructorpublic class FormTemplateController { private final FormTemplateService formTemplateService; private final FormTemplateCategoryService formTemplateCategoryService; private final UserFormItemService userFormItemService; private final UserFormService userFormService; private final UserFormLogicService userFormLogicService; private final UserFormThemeService userFormThemeService; /** * 删除模板 * * @param templateEntity * @return */ @PostMapping("/form/template/delete") public Result deleteFormTemplate(@RequestBody FormTemplateEntity templateEntity) { formTemplateService.remove(Wrappers.<FormTemplateEntity>lambdaQuery().eq(FormTemplateEntity::getFormKey, templateEntity.getFormKey())); return Result.success(templateEntity.getFormKey()); } /** * 分页查询项目分类 * * @return */ @GetMapping("/form/template/type/list") public Result queryFormTemplateTypes(QueryFormTemplateTypeRequest.List request) { return Result.success(formTemplateCategoryService.list(Wrappers.<FormTemplateCategoryEntity>lambdaQuery() .orderByDesc(FormTemplateCategoryEntity::getSort))); } /** * 分页查询项目模板 * * @return */ @GetMapping("/form/template/page") public Result queryFormTemplates(QueryFormTemplateRequest.Page request) { return Result.success( formTemplateService.page(request.toMybatisPage(), Wrappers.<FormTemplateEntity>lambdaQuery() .eq(ObjectUtil.isNotNull(request.getType()), FormTemplateEntity::getCategoryId, request.getType()) .like(StrUtil.isNotBlank(request.getName()), FormTemplateEntity::getName, request.getName()) .orderByDesc(FormTemplateEntity::getCreateTime))); } /** * 表单另存为为模板 * * @param userId 用户id * @return */ @PostMapping("/form/template/create") public Result createFormTemplate(@RequestBody FormTemplateEntity formTemplateEntity, @RequestAttribute Long userId) { FormTemplateEntity formTemplate = formTemplateService.createFormTemplate(formTemplateEntity); return Result.success(formTemplate.getFormKey()); } /** * 查询项目模板详情 * 包含项目信息 项目保单项信息 * * @param key 项目key * @return */ @GetMapping("/form/template/details/{key}") public Result queryFormTemplateDetails(@PathVariable @NotBlank String key) { FormTemplateEntity templateEntity = formTemplateService.getByKey(key); return Result.success(templateEntity.getScheme()); } /** * 查询项目模板分类列表 */ @GetMapping("/form/template/category/page") public Result queryCategoryPage(Page page, FormTemplateCategoryEntity fmFormTemplateCategory) { return Result.success(formTemplateCategoryService.page(page, QueryWrapperUtils.toSimpleQuery(fmFormTemplateCategory))); } /** * 获取项目模板分类详细信息 */ @GetMapping(value = "/form/template/category/{id}") public Result getCategoryInfo(@PathVariable("id") Long id) { return Result.success(formTemplateCategoryService.getById(id)); } /** * 新增项目模板分类 */ @PostMapping("/form/template/category") public Result saveCategory(@RequestBody FormTemplateCategoryEntity fmFormTemplateCategory) { return Result.success(formTemplateCategoryService.save(fmFormTemplateCategory)); } /** * 修改项目模板分类 */ @PutMapping("/form/template/category") public Result updateCategory(@RequestBody FormTemplateCategoryEntity fmFormTemplateCategory) { return Result.success(formTemplateCategoryService.updateById(fmFormTemplateCategory)); } /** * 删除项目模板分类 */ @DeleteMapping("/form/template/category/{ids}") public Result deleteCategory(@PathVariable List<Long> ids) { return Result.success(formTemplateCategoryService.removeByIds(ids)); }}
package com.strongdata.jsurvey.api.web.controller;import cn.hutool.core.util.ObjectUtil;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.jsurvey.common.util.QueryWrapperUtils;import com.strongdata.jsurvey.common.util.Result;import com.strongdata.jsurvey.form.entity.FormThemeCategoryEntity;import com.strongdata.jsurvey.form.entity.FormThemeEntity;import com.strongdata.jsurvey.form.request.QueryProThemeRequest;import com.strongdata.jsurvey.form.service.FormThemeService;import lombok.RequiredArgsConstructor;import org.springframework.web.bind.annotation.*;import java.util.List;/** * 表单主题 * * * @description : * @create : 2022/10/19 14:41 **/@RestController@RequestMapping("/form/")@RequiredArgsConstructorpublic class FormThemeController { private final FormThemeService formThemeService; /** * 查询项目主题外观模板列表 * @param request 查询参数 * @return Result */ @GetMapping("theme/list") public Result queryThemes(QueryProThemeRequest request) { List<FormThemeEntity> list = formThemeService.list(Wrappers.<FormThemeEntity>lambdaQuery() .eq(ObjectUtil.isNotNull(request.getStyle()), FormThemeEntity::getStyle, request.getStyle())); return Result.success(list); } /** * 查询项目主题外观模板列表 */ @GetMapping("/theme/page") public Result queryPage(Page page, FormThemeEntity themeEntity) { return Result.success(formThemeService.page(page, QueryWrapperUtils.toSimpleQuery(themeEntity))); } /** * 获取项目主题外观模板详细信息 */ @GetMapping(value = "/theme/{id}") public Result getInfo(@PathVariable("id") Long id) { return Result.success(formThemeService.getById(id)); } /** * 新增项目主题外观模板 */ @PostMapping("/theme") public Result save(@RequestBody FormThemeEntity formTheme) { return Result.success(formThemeService.save(formTheme)); } /** * 修改项目主题外观模板 */ @PutMapping("/theme") public Result update(@RequestBody FormThemeEntity fmFormTheme) { return Result.success(formThemeService.updateById(fmFormTheme)); } /** * 删除项目主题外观模板 */ @DeleteMapping("/theme/{ids}") public Result delete(@PathVariable List<Long> ids) { return Result.success(formThemeService.removeByIds(ids)); } /** * 查询项目主题外观模板列表 */ @GetMapping("/theme/category/list") public Result queryCategoryList() { return Result.success(formThemeService.listThemeCategories()); } /** * 获取表单主题分类详细信息 */ @GetMapping(value = "/theme/category/{id}") public Result getCategoryInfo(@PathVariable("id") Long id) { return Result.success(formThemeService.getThemeCategory(id)); } /** * 新增单主题分类 */ @PostMapping("/theme/category") public Result saveCategory(@RequestBody FormThemeCategoryEntity formThemeCategory) { return Result.success(formThemeService.saveThemeCategory(formThemeCategory)); } /** * 修改单主题分类 */ @PutMapping("/theme/category") public Result updateCategory(@RequestBody FormThemeCategoryEntity fmFormThemeCategory) { return Result.success(formThemeService.updateThemeCategory(fmFormThemeCategory)); } /** * 删除单主题分类 */ @DeleteMapping("/theme/category/{ids}") public Result deleteCategory(@PathVariable List<Long> ids) { return Result.success(formThemeService.deleteThemeCategory(ids)); }}
package com.strongdata.jsurvey.api.web.controller;import com.strongdata.jsurvey.api.annotation.NotLogin;import com.strongdata.jsurvey.common.util.Result;import com.strongdata.jsurvey.envconfig.service.SysEnvConfigService;import lombok.RequiredArgsConstructor;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import static com.strongdata.jsurvey.envconfig.constant.ConfigConstants.SYSTEM_INFO_CONFIG;/** * 公开接口 * * */@RestController@RequiredArgsConstructor@RequestMapping("/public/")public class PublicController { private final SysEnvConfigService configService; /*** * 获取系统信息配置 * @return 系统信息配置 */ @GetMapping("systemInfoConfig") @NotLogin public Result<String> getSystemInfoConfig() { return Result.success(configService.getValueByKey(SYSTEM_INFO_CONFIG)); }}
package com.strongdata.jsurvey.api.web.controller;import com.strongdata.jsurvey.common.util.Result;import com.strongdata.jsurvey.envconfig.entity.SysEnvConfigEntity;import com.strongdata.jsurvey.envconfig.service.SysEnvConfigService;import lombok.RequiredArgsConstructor;import org.springframework.validation.annotation.Validated;import org.springframework.web.bind.annotation.*;/** * 参数配置 信息操作处理 * * */@RestController@RequiredArgsConstructor@RequestMapping("/system/env/config")public class SysEnvConfigController { private final SysEnvConfigService configService; /** * 保存系统环境配置 */ @PostMapping("/save") public Result save(@RequestBody @Validated SysEnvConfigEntity config) { configService.saveConfig(config); return Result.success(); } /** * 根据参数编号获取详细信息 */ @GetMapping(value = "/{configKey}") public Result getInfo(@PathVariable String configKey) { return Result.success(configService.getByKey(configKey)); } /** * 根据参数编号获取详细信息 */ @GetMapping(value = "/value/{configKey}") public Result getConfigValue(@PathVariable String configKey) { return Result.success(configService.getValueByKey(configKey)); }}
package com.strongdata.jsurvey.api.web.controller;import cn.hutool.core.io.FileUtil;import cn.hutool.core.util.CharUtil;import cn.hutool.core.util.IdUtil;import cn.hutool.crypto.SecureUtil;import com.strongdata.jsurvey.common.util.Result;import com.strongdata.jsurvey.storage.cloud.OssStorageFactory;import lombok.RequiredArgsConstructor;import org.springframework.web.bind.annotation.*;import org.springframework.web.multipart.MultipartFile;import javax.annotation.security.PermitAll;import java.io.IOException;/** * 表单文件上传 * * * @description : 上传文件 * @create : 2022-11-27 14:00 **/@RestController@RequiredArgsConstructorpublic class UploadFileController { /** * 上传用户文件 * <p> * 用户Id MD5加密 同一个用户的文件放在一个目录下 * * @param file * @param userId * @return * @throws IOException */ @PostMapping("/user/file/upload") public Result<String> uploadUserFile(@RequestParam("file") MultipartFile file, @RequestAttribute Long userId) throws IOException { String path = SecureUtil.md5(String.valueOf(userId)) + CharUtil.SLASH + IdUtil.simpleUUID() + CharUtil.DOT + FileUtil.extName(file.getOriginalFilename()); String url = OssStorageFactory.getStorageService().upload(file.getInputStream(), path); return Result.success(url); } /** * 表单文件上传 * * @param file 文件 * @param formKey 表单key * @return 文件地址 * @throws IOException IO异常 */ @PostMapping("/form/file/upload/{formKey}") @PermitAll public Result<String> uploadFormFile(@RequestParam("file") MultipartFile file, @PathVariable("formKey") String formKey) throws IOException { String path = SecureUtil.md5(formKey) + CharUtil.SLASH + IdUtil.simpleUUID() + CharUtil.DOT + FileUtil.extName(file.getOriginalFilename()); String url = OssStorageFactory.getStorageService().upload(file.getInputStream(), path); return Result.success(url); }}
package com.strongdata.jsurvey.api.web.controller;import cn.hutool.core.bean.BeanUtil;import cn.hutool.core.lang.Validator;import cn.hutool.core.util.ObjectUtil;import com.strongdata.jsurvey.account.entity.UserAuthorizeEntity;import com.strongdata.jsurvey.account.entity.UserEntity;import com.strongdata.jsurvey.account.entity.enums.UserAuthorizeTypeEnum;import com.strongdata.jsurvey.account.request.QqLoginRequest;import com.strongdata.jsurvey.account.request.UpdateUserRequest;import com.strongdata.jsurvey.account.service.UserAuthorizeService;import com.strongdata.jsurvey.account.service.UserService;import com.strongdata.jsurvey.account.service.UserValidateService;import com.strongdata.jsurvey.account.util.PasswordUtils;import com.strongdata.jsurvey.account.vo.UserDetailVO;import com.strongdata.jsurvey.api.annotation.LoginUser;import com.strongdata.jsurvey.common.util.JsonUtils;import com.strongdata.jsurvey.common.util.Result;import com.strongdata.jsurvey.common.validator.ValidatorUtils;import com.strongdata.jsurvey.wx.mp.entity.WxMpUserEntity;import com.strongdata.jsurvey.wx.mp.request.WxMpQrCodeGenRequest;import com.strongdata.jsurvey.wx.mp.service.WxMpUserService;import lombok.RequiredArgsConstructor;import me.chanjar.weixin.common.error.WxErrorException;import me.chanjar.weixin.mp.api.WxMpService;import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;import org.springframework.web.bind.annotation.*;/** * * @description : * @create : 2022-12-18 15:50 **/@RequestMapping("/user")@RestController@RequiredArgsConstructorpublic class UserController { private final UserService userService; private final UserAuthorizeService userAuthorizeService; private final WxMpUserService wxMpUserService; private final UserValidateService userValidateService; private final WxMpService wxMpService; /*** * 当前登录用户详情 * @param userId * @return */ @GetMapping("/current/detail") public Result queryCurrentUser(@RequestAttribute Long userId) { UserEntity userEntity = userService.getById(userId); UserDetailVO userDetailVO = new UserDetailVO(); BeanUtil.copyProperties(userEntity, userDetailVO); //第三方账号信息 UserAuthorizeEntity authorizeEntity = userAuthorizeService.getByUserId(UserAuthorizeTypeEnum.QQ, userId); if (ObjectUtil.isNotNull(authorizeEntity)) { userDetailVO.setQqName(authorizeEntity.getUserName()); } WxMpUserEntity wxMpUserEntity = wxMpUserService.getByUserId(userId); if (ObjectUtil.isNotNull(wxMpUserEntity)) { userDetailVO.setWxName(wxMpUserEntity.getNickname()); } userDetailVO.setAdmin(userEntity.isAdmin()); return Result.success(userDetailVO); } /*** * 修改当前用户信息 * @param userEntity * @return */ @PostMapping("/update") public Result updateUser(@RequestBody UserEntity userEntity, @RequestAttribute Long userId) { userEntity.setPassword(null); userEntity.setId(userId); return Result.success(userService.updateById(userEntity)); } /** * 发送绑定邮箱邮件 * * @return */ @GetMapping("/update-email/msg") public Result sendUpdateEmailMsg(@RequestParam String email, @RequestAttribute Long userId) { Validator.validateEmail(email, "邮箱地址不正确"); UserEntity userEntity = userService.getUserByEmail(email); if (ObjectUtil.isNotNull(userEntity)) { return Result.failed("该邮箱已被绑定"); } userValidateService.sendUpdateAccountEmail(email, userId); return Result.success(true); } /** * 修改邮箱 * * @return */ @PostMapping("/update/email") public Result updateUserEmail(@RequestBody UpdateUserRequest.Email request) { Validator.validateEmail(request.getEmail(), "邮箱地址不正确"); UserEntity userEntity = userService.getUserByEmail(request.getEmail()); if (ObjectUtil.isNotNull(userEntity)) { return Result.failed("该邮箱已被绑定"); } Long userId = userValidateService.getUpdateEmailUserId(request); if (ObjectUtil.isNull(userId)) { return Result.success(false); } userEntity = new UserEntity(); userEntity.setId(userId); userEntity.setEmail(request.getEmail()); userService.updateById(userEntity); return Result.success(true); } /** * 绑定微信二维码 * * @return */ @GetMapping("/bind/wx/qrcode") public Result getBindWxQrcode(@RequestAttribute Long userId) throws WxErrorException { String bindSceneStr = JsonUtils.objToJson(new WxMpQrCodeGenRequest(WxMpQrCodeGenRequest.QrCodeType.BIND_ACCOUNT, String.valueOf(userId))); //5分钟有效 WxMpQrCodeTicket ticket = wxMpService.getQrcodeService().qrCodeCreateTmpTicket(bindSceneStr, 10 * 60); String bindAccountQrcodeUrl = wxMpService.getQrcodeService().qrCodePictureUrl(ticket.getTicket()); return Result.success(bindAccountQrcodeUrl); } /** * 修改密码e * * @return */ @PostMapping("/update/password") public Result updatePassword(@RequestBody UpdateUserRequest.Password request, @LoginUser UserEntity userEntity) { ValidatorUtils.validateEntity(request); if (!PasswordUtils.checkPassword(userEntity, request.getOldPassword())) { return Result.failed("旧密码错误"); } if (!request.getPassword().equals(request.getRepeatPassword())) { return Result.failed("两次密码不一致"); } userService.updatePassword(userEntity.getId(), request.getPassword()); return Result.success(); } /** * 绑定qq账号 * * @return */ @PostMapping("/bind/qq") public Result bindQQAccount(@RequestBody QqLoginRequest request, @RequestAttribute Long userId) { UserAuthorizeEntity authorizeEntity = userAuthorizeService.getQqAuthorization(request.getAuthorizeCode(), request.getRedirectUri(), new UserEntity()); if (ObjectUtil.isNotNull(authorizeEntity.getUserId()) && userId.equals(authorizeEntity.getUserId())) { return Result.success(false); } //更新绑定 authorizeEntity.setUserId(userId); userAuthorizeService.updateById(authorizeEntity); return Result.success(); }}
package com.strongdata.jsurvey.api.web.controller;import cn.hutool.core.lang.tree.TreeNode;import cn.hutool.core.lang.tree.TreeUtil;import cn.hutool.core.util.ObjectUtil;import cn.hutool.core.util.StrUtil;import cn.hutool.json.JSONObject;import cn.hutool.json.JSONUtil;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.jsurvey.common.constant.CommonConstants;import com.strongdata.jsurvey.common.entity.BaseEntity;import com.strongdata.jsurvey.common.util.Result;import com.strongdata.jsurvey.common.validator.ValidatorUtils;import com.strongdata.jsurvey.common.validator.group.AddGroup;import com.strongdata.jsurvey.common.validator.group.UpdateGroup;import com.strongdata.jsurvey.form.entity.*;import com.strongdata.jsurvey.form.service.*;import com.strongdata.jsurvey.form.entity.enums.FormSourceTypeEnum;import com.strongdata.jsurvey.form.entity.enums.FormStatusEnum;import com.strongdata.jsurvey.form.entity.enums.FormTypeEnum;import com.strongdata.jsurvey.form.request.QueryFormItemRequest;import com.strongdata.jsurvey.form.request.QueryFormRequest;import com.strongdata.jsurvey.form.request.SortFormItemRequest;import com.strongdata.jsurvey.form.util.FormAuthUtils;import com.strongdata.jsurvey.form.util.FormDataUtils;import com.strongdata.jsurvey.form.util.ShortIdUtils;import com.strongdata.jsurvey.form.util.SortUtils;import com.strongdata.jsurvey.form.vo.FormFieldVO;import com.strongdata.jsurvey.form.vo.OperateFormItemVO;import com.strongdata.jsurvey.form.vo.RecycleFormVO;import com.strongdata.jsurvey.form.vo.UserFormDetailVO;import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;import org.springframework.web.bind.annotation.*;import javax.annotation.security.PermitAll;import javax.validation.constraints.NotBlank;import java.util.ArrayList;import java.util.Comparator;import java.util.List;import java.util.stream.Collectors;/** * 用户表单 * * * @description : 用户表单 * @create : 2022-11-18 18:17 **/@RequiredArgsConstructor@RestController@Slf4jpublic class UserFormController { private final UserFormService formService; private final UserFormItemService formItemService; private final UserFormDataService userFormDataService; private final SortUtils sortUtils; private final UserFormThemeService userFormThemeService; private final UserFormSettingService userFormSettingService; private final FormTemplateService formTemplateService; private final UserFormLogicService userFormLogicService; /** * 创建表单 */ @PostMapping("/user/form/create") public Result createForm(@RequestBody UserFormEntity form, @RequestAttribute Long userId) { if (ObjectUtil.isNotNull(form.getFolderId()) && 0 != form.getFolderId()) { // 检查文件夹是否存在 long count = formService.count(Wrappers.<UserFormEntity>lambdaQuery().eq(BaseEntity::getId, form.getFolderId()).eq(UserFormEntity::getDeleted, 0)); if (count == 0) { return Result.failed("文件夹不存在"); } } ValidatorUtils.validateEntity(form, AddGroup.class); form.setFormKey(ShortIdUtils.genId()); form.setUserId(userId); form.setStatus(FormStatusEnum.CREATE); form.setSourceType(FormSourceTypeEnum.BLANK); form.setDeleted(false); formService.save(form); return Result.success(form); } /** * 从模板创建表单 */ @PostMapping("/user/form/use-template/create") public Result createFormByTemplate(@RequestBody FormTemplateEntity request, @RequestAttribute Long userId) { UserFormEntity userForm = formTemplateService.createFormByTemplate(request, userId); return Result.success(userForm.getFormKey()); } /** * 根据条件查询所有表单 */ @GetMapping("/user/form/list") public Result listForms(QueryFormRequest.List request, @RequestAttribute Long userId) { List<UserFormEntity> entityList = formService.list(Wrappers.<UserFormEntity>lambdaQuery().eq(UserFormEntity::getUserId, userId).eq(ObjectUtil.isNotNull(request.getStatus()), UserFormEntity::getStatus, request.getStatus()).orderByDesc(BaseEntity::getUpdateTime)); return Result.success(entityList); } /** * 查询我的表单分页 */ @GetMapping("/user/form/page") public Result queryMyForms(@RequestAttribute Long userId, QueryFormRequest.Page request) { LambdaQueryWrapper<UserFormEntity> queryWrapper = Wrappers.<UserFormEntity>lambdaQuery().eq(UserFormEntity::getUserId, userId) .eq(ObjectUtil.isNotNull(request.getFolder()), UserFormEntity::getFolder, request.getFolder()) .eq(ObjectUtil.isNotNull(request.getType()), UserFormEntity::getType, request.getType()) .eq(UserFormEntity::getDeleted, 0).func(i -> { // 通过文件名搜索时 可以搜索到子文件夹下的表单 if (StrUtil.isNotBlank(request.getName()) && request.getFolderId() == 0) { } else { i.eq(UserFormEntity::getFolderId, request.getFolderId()); } }).eq(ObjectUtil.isNotNull(request.getStatus()), UserFormEntity::getStatus, request.getStatus()).like(StrUtil.isNotBlank(request.getName()), UserFormEntity::getName, request.getName()).le(ObjectUtil.isNotNull(request.getEndDateTime()), UserFormEntity::getUpdateTime, request.getEndDateTime()).ge(ObjectUtil.isNotNull(request.getBeginDateTime()), UserFormEntity::getUpdateTime, request.getBeginDateTime()).orderByDesc(UserFormEntity::getFolder).orderByDesc(BaseEntity::getCreateTime); return Result.success(formService.page(request.toMybatisPage(), queryWrapper)); } /** * 查询表单文件夹树 */ @GetMapping("/user/form/folderTree") public Result queryMyFormFolderTree(@RequestAttribute Long userId) { List<UserFormEntity> list = formService.list(Wrappers.<UserFormEntity>lambdaQuery().eq(UserFormEntity::getUserId, userId).eq(UserFormEntity::getFolder, 1)); List<TreeNode<Long>> nodeList = list.stream().map(item -> new TreeNode<>(item.getId(), item.getFolderId(), item.getName(), 5)).collect(Collectors.toList()); return Result.success(TreeUtil.build(nodeList, 0L)); } /** * 查询表单 */ @GetMapping("/user/form/{key}") public Result queryFormByKey(@PathVariable @NotBlank String key) { return Result.success(formService.getByKey(key)); } /** * 发布表单 */ @PostMapping("/user/form/publish") public Result publishForm(@RequestBody UserFormEntity request) { FormAuthUtils.hasPermission(request.getFormKey()); long count = formItemService.count(Wrappers.<UserFormItemEntity>lambdaQuery().eq(UserFormItemEntity::getFormKey, request.getFormKey())); if (count == CommonConstants.ConstantNumber.ZERO) { return Result.failed("无有效表单项,无法发布"); } UserFormEntity entity = formService.getByKey(request.getFormKey()); entity.setStatus(FormStatusEnum.RELEASE); return Result.success(formService.updateById(entity)); } /** * 停止收集 * * @param request */ @PostMapping("/user/form/stop") public Result stopForm(@RequestBody UserFormEntity request) { FormAuthUtils.hasPermission(request.getFormKey()); UserFormEntity entity = formService.getByKey(request.getFormKey()); entity.setStatus(FormStatusEnum.STOP); return Result.success(formService.updateById(entity)); } /** * 删除表单到回收站 * * @param request */ @PostMapping("/user/form/logic/delete") public Result logicDeleteForm(@RequestBody UserFormEntity request) { FormAuthUtils.hasPermission(request.getFormKey()); boolean del = formService.update(new UserFormEntity() {{ setDeleted(Boolean.TRUE); }}, Wrappers.<UserFormEntity>lambdaQuery().eq(UserFormEntity::getFormKey, request.getFormKey())); return Result.success(del); } /** * 删除 * * @param request */ @PostMapping("/user/form/delete") public Result deleteForm(@RequestBody UserFormEntity request) { // 如果文件夹下面存在表单 不允许删除 FormAuthUtils.hasPermission(request.getFormKey()); UserFormEntity formEntity = formService.getOne(Wrappers.<UserFormEntity>lambdaQuery().eq(UserFormEntity::getFormKey, request.getFormKey())); if (formEntity.getFolder()) { long count = formService.count(Wrappers.<UserFormEntity>lambdaQuery().eq(UserFormEntity::getDeleted, 0).eq(UserFormEntity::getFolderId, formEntity.getId())); if (count > 0) { return Result.failed("当前文件夹下存在表单,不允许删除"); } } boolean del = formService.remove(Wrappers.<UserFormEntity>lambdaQuery().eq(UserFormEntity::getFormKey, request.getFormKey())); return Result.success(del); } /** * 查询表单详情 * 包含表单信息 表单字段信息 表单主题 * * @param key */ @GetMapping("/user/form/details/{key}") @PermitAll public Result queryFormDetails(@PathVariable @NotBlank String key) { UserFormEntity form = formService.getByKey(key); if (ObjectUtil.isNull(form)) { return Result.success(); } List<UserFormItemEntity> formItemList = formItemService.list(Wrappers.<UserFormItemEntity>lambdaQuery().ne(UserFormItemEntity::getHideType, 1).eq(UserFormItemEntity::getFormKey, key)); formItemList.sort(Comparator.comparing(UserFormItemEntity::getSort)); UserFormThemeEntity theme = userFormThemeService.getByKey(key); UserFormLogicEntity formLogic = userFormLogicService.getOne(Wrappers.<UserFormLogicEntity>lambdaQuery().eq(UserFormLogicEntity::getFormKey, key)); // 如果是考试 移除正确答案 避免把正确答案返回到前端 if (form.getType() == FormTypeEnum.EXAM) { formItemList.forEach(item -> { JSONObject schemeJson = JSONUtil.parseObj(item.getScheme()); if (schemeJson.containsKey("examConfig")) { schemeJson.getJSONObject("examConfig").remove("answer"); } item.setScheme(schemeJson); }); } return Result.success(new UserFormDetailVO(new UserFormDetailVO.UserForm(form), formItemList, theme, formLogic)); } /** * 表单更新 * * @param form * @param userId */ @PostMapping("/user/form/update") public Result updateForm(@RequestBody UserFormEntity form, @RequestAttribute Long userId) { ValidatorUtils.validateEntity(form, AddGroup.class); UserFormEntity oldForm = formService.getByKey(form.getFormKey()); if (ObjectUtil.isNotNull(oldForm) && userId.equals(oldForm.getUserId())) { form.setId(oldForm.getId()); formService.updateById(form); } return Result.success(); } /** * 项目表单项查询 */ @GetMapping("/user/form/item/list") public Result queryFormItems(QueryFormItemRequest request) { ValidatorUtils.validateEntity(request); FormAuthUtils.hasPermission(request.getKey()); List<UserFormItemEntity> itemEntityList = formItemService.list(Wrappers.<UserFormItemEntity>lambdaQuery().eq(UserFormItemEntity::getFormKey, request.getKey()).eq(ObjectUtil.isNotNull(request.getDisplayType()), UserFormItemEntity::getDisplayType, request.getDisplayType())); itemEntityList.sort(Comparator.comparing(UserFormItemEntity::getSort)); return Result.success(itemEntityList); } /** * 获取表单字段 包括系统默认字段 */ @GetMapping("/user/form/fields/{formKey}") public Result queryUserFormFields(@PathVariable String formKey) { return Result.success(formItemService.listAllFormFields(formKey)); } /** * 获取表单固定字段 * 所有表单都包含 用于查看详情右侧显示 */ @GetMapping("/user/form/fixed/fields/{formKey}") public Result queryUserFormFixedFields(@PathVariable String formKey) { // 查询表单类型 UserFormEntity userFormEntity = formService.getByKey(formKey); List<FormFieldVO> fields = new ArrayList<>(); FormDataUtils.addFormBaseDataField(fields); fields.add(new FormFieldVO("submitUaOs", "操作系统")); fields.add(new FormFieldVO("submitUaDevice", "设备")); fields.add(new FormFieldVO(UserFormDataEntity.Fields.submitBrowser, "浏览器")); fields.add(new FormFieldVO(UserFormDataEntity.Fields.submitAddress, "地址")); fields.add(new FormFieldVO(UserFormDataEntity.Fields.submitRequestIp, "IP")); fields.add(new FormFieldVO(UserFormDataEntity.Fields.wxUserInfo, "微信用户")); return Result.success(fields); } /** * 项目表单项创建 * * @param entity */ @PostMapping("/user/form/item/create") public Result createFormItem(@RequestBody UserFormItemEntity entity) { ValidatorUtils.validateEntity(entity, AddGroup.class); if (ObjectUtil.isNull(entity.getDisplayType())) { entity.setDisplayType(false); } if (ObjectUtil.isNull(entity.getHideType())) { entity.setHideType(false); } //排序下标计算 entity.setSort(sortUtils.getInitialSortPosition(entity.getFormKey())); entity.setSpecialType(formItemService.isSpecialTypeItem(entity)); boolean save = formItemService.save(entity); return Result.success(new OperateFormItemVO(entity.getSort(), entity.getId(), save, false)); } /** * 批量项目表单项创建 */ @PostMapping("/user/form/item/batch/create") public Result batchCreateFormItem(@RequestBody List<UserFormItemEntity> itemEntityList) { //排序下标计算 itemEntityList.forEach(item -> item.setSort(sortUtils.getInitialSortPosition(item.getFormKey()))); boolean save = formItemService.saveBatch(itemEntityList); return Result.success(); } /** * 表单项更新 * * @param request */ @PostMapping("/user/form/item/update") public Result updateFormItem(@RequestBody UserFormItemEntity request) { FormAuthUtils.hasPermission(request.getFormKey()); ValidatorUtils.validateEntity(request, UpdateGroup.class); request.setSpecialType(formItemService.isSpecialTypeItem(request)); boolean update = formItemService.update(request, Wrappers.<UserFormItemEntity>lambdaQuery().eq(UserFormItemEntity::getFormKey, request.getFormKey()).eq(UserFormItemEntity::getFormItemId, request.getFormItemId())); return Result.success(update); } /** * 表单项删除 */ @PostMapping("/user/form/item/delete") public Result deleteFormItem(@RequestBody UserFormItemEntity request) { FormAuthUtils.hasPermission(request.getFormKey()); boolean delete = formItemService.remove(Wrappers.<UserFormItemEntity>lambdaQuery().eq(UserFormItemEntity::getFormKey, request.getFormKey()).eq(UserFormItemEntity::getFormItemId, request.getFormItemId())); return Result.success(delete); } /** * 表单项排序 * * @param request */ @PostMapping("/user/form/item/sort") public Result sortFormItem(@RequestBody SortFormItemRequest request) { ValidatorUtils.validateEntity(request); if (ObjectUtil.isNull(request.getAfterPosition()) && ObjectUtil.isNull(request.getBeforePosition())) { return Result.success(); } UserFormItemEntity itemEntity = formItemService.getOne(Wrappers.<UserFormItemEntity>lambdaQuery().eq(UserFormItemEntity::getFormKey, request.getFormKey()).eq(UserFormItemEntity::getFormItemId, request.getFormItemId())); Long sort = sortUtils.calcSortPosition(request.getBeforePosition(), request.getAfterPosition(), request.getFormKey()); if (sortUtils.sortAllList(request.getBeforePosition(), request.getAfterPosition(), request.getFormKey(), sort)) { return Result.success(new OperateFormItemVO(itemEntity.getSort(), itemEntity.getId(), true, true)); } itemEntity.setSort(sort); boolean b = formItemService.updateById(itemEntity); return Result.success(new OperateFormItemVO(itemEntity.getSort(), itemEntity.getId(), b, false)); } /** * 项目主题保存 * * @param themeEntity */ @PostMapping("/user/form/theme/save") public Result saveFormTheme(@RequestBody UserFormThemeEntity themeEntity) { ValidatorUtils.validateEntity(themeEntity); FormAuthUtils.hasPermission(themeEntity.getFormKey()); if (ObjectUtil.isNull(themeEntity.getShowSubmitBtn())) { themeEntity.setShowSubmitBtn(true); } UserFormThemeEntity entity = userFormThemeService.getOne(Wrappers.<UserFormThemeEntity>lambdaQuery().eq(UserFormThemeEntity::getFormKey, themeEntity.getFormKey())); if (ObjectUtil.isNotNull(entity)) { themeEntity.setId(entity.getId()); } return Result.success(userFormThemeService.saveOrUpdate(themeEntity)); } /** * 项目主题查询 * * @param formKey */ @GetMapping("/user/form/theme/{key}") public Result queryThemeByKey(@PathVariable("key") String formKey) { FormAuthUtils.hasPermission(formKey); UserFormThemeEntity entity = userFormThemeService.getOne(Wrappers.<UserFormThemeEntity>lambdaQuery().eq(UserFormThemeEntity::getFormKey, formKey)); return Result.success(entity); } /** * 回收站项目分页 */ @GetMapping("/user/form/recycle/page") public Result queryRecycleForms(@RequestAttribute Long userId, QueryFormRequest.Page request) { Page page = formService.page(request.toMybatisPage(), Wrappers.<UserFormEntity>lambdaQuery().eq(UserFormEntity::getUserId, userId).eq(UserFormEntity::getDeleted, 1).orderByDesc(BaseEntity::getUpdateTime)); List<UserFormEntity> records = page.getRecords(); List<RecycleFormVO> FormVOList = records.stream().map(item -> { long count = userFormDataService.count(Wrappers.<UserFormDataEntity>lambdaQuery().eq(UserFormDataEntity::getFormKey, item.getFormKey())); return new RecycleFormVO(item.getFormKey(), count, item.getTextName(), item.getCreateTime(), item.getUpdateTime()); }).collect(Collectors.toList()); page.setRecords(FormVOList); return Result.success(page); } /** * 从回收站中恢复项目 */ @PostMapping("/user/form/recycle/restore") public Result restoreRecycleForm(@RequestBody UserFormEntity request) { boolean flag = formService.update(new UserFormEntity() {{ setDeleted(Boolean.FALSE); }}, Wrappers.<UserFormEntity>lambdaQuery().eq(UserFormEntity::getFormKey, request.getFormKey())); return Result.success(flag); } /** * 从回收站中删除项目 */ @PostMapping("/user/form/recycle/delete") public Result deleteRecycleForm(@RequestAttribute Long userId, @RequestBody UserFormEntity FormEntity) { boolean remove = formService.remove(Wrappers.<UserFormEntity>lambdaQuery().eq(UserFormEntity::getUserId, userId).eq(UserFormEntity::getFormKey, FormEntity.getFormKey())); if (remove) { userFormThemeService.remove(Wrappers.<UserFormThemeEntity>lambdaQuery().eq(UserFormThemeEntity::getFormKey, FormEntity.getFormKey())); userFormSettingService.deleteAllSetting(FormEntity.getFormKey()); } return Result.success(remove); }}
package com.strongdata.jsurvey.api.web.controller;import cn.hutool.core.util.ObjectUtil;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.strongdata.jsurvey.common.util.Result;import com.strongdata.jsurvey.form.entity.UserFormLogicEntity;import com.strongdata.jsurvey.form.service.UserFormLogicService;import com.strongdata.jsurvey.form.util.FormAuthUtils;import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;import org.springframework.web.bind.annotation.*;import javax.validation.constraints.NotBlank;/** * 表单逻辑 * * * @description : 表单逻辑 * @create : 2022-11-18 18:17 **/@Slf4j@RestController@RequiredArgsConstructorpublic class UserFormLogicController { private final UserFormLogicService formLogicService; /** * 保存表单逻辑 * * @param userFormLogicEntity 表单逻辑 * @return 表单逻辑 */ @PostMapping("/user/form/logic/save") public Result saveUserFormLogic(@RequestBody UserFormLogicEntity userFormLogicEntity) { FormAuthUtils.hasPermission(userFormLogicEntity.getFormKey()); UserFormLogicEntity formLogic = formLogicService.getOne(Wrappers.<UserFormLogicEntity>lambdaQuery().eq(UserFormLogicEntity::getFormKey, userFormLogicEntity.getFormKey())); if (ObjectUtil.isNotNull(formLogic)) { userFormLogicEntity.setId(formLogic.getId()); formLogicService.updateById(userFormLogicEntity); } else { formLogicService.save(userFormLogicEntity); } return Result.success(userFormLogicEntity); } /** * 查询表单逻辑 * * @param formKey 表单key * @return 表单逻辑 */ @GetMapping("/user/form/logic") public Result queryFormLogic(@RequestParam @NotBlank String formKey) { FormAuthUtils.hasPermission(formKey); return Result.success(formLogicService.getOne(Wrappers.<UserFormLogicEntity>lambdaQuery().eq(UserFormLogicEntity::getFormKey, formKey))); }}
package com.strongdata.jsurvey.api.web.controller;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.strongdata.jsurvey.common.util.Result;import com.strongdata.jsurvey.form.entity.UserFormLinkExtEntity;import com.strongdata.jsurvey.form.service.UserFormLinkExtService;import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;import org.springframework.web.bind.annotation.*;import java.util.List;/** * 表单发布 * * * @description : 用户表单发布 * @create : 2022-11-18 18:17 **/@Slf4j@RestController@RequiredArgsConstructorpublic class UserFormPublishController { private final UserFormLinkExtService formLinkExtService; /** * 获取表单扩展字段列表 * * @param formKey * @return */ @GetMapping("/user/form/link/extList/{formKey}") public Result listUserFormLinkExt(@PathVariable String formKey) { List<UserFormLinkExtEntity> list = formLinkExtService.list(Wrappers.<UserFormLinkExtEntity>lambdaQuery() .eq(UserFormLinkExtEntity::getFormKey, formKey)); return Result.success(list); } /** * 获取表单扩展字段列表 * * @param entity * @return */ @PostMapping("/user/form/link/ext") public Result saveUserFormLinkExt(@RequestBody UserFormLinkExtEntity entity) { long count = formLinkExtService.count(Wrappers.<UserFormLinkExtEntity>lambdaQuery() .eq(UserFormLinkExtEntity::getFormKey, entity.getFormKey()).eq(UserFormLinkExtEntity::getExtValue, entity.getExtValue())); if (count > 0) { return Result.failed("已存在该扩展名称"); } formLinkExtService.save(entity); return Result.success(); } /** * 获取表单扩展字段列表 * * @param entity * @return */ @PostMapping("/user/form/link/ext/delete") public Result deleteUserFormLinkExt(@RequestBody UserFormLinkExtEntity entity) { formLinkExtService.remove(Wrappers.<UserFormLinkExtEntity>lambdaQuery() .eq(UserFormLinkExtEntity::getFormKey, entity.getFormKey()).eq(UserFormLinkExtEntity::getExtValue, entity.getExtValue())); return Result.success(); }}