♻️ 重构代码

This commit is contained in:
冷冷 committed 2018-10-04 13:43:50 +08:00
1 parent 4de4f6c349
commit ea6072eb4a
19 files changed
+125 -106

No files matched your search

@@ -24,6 +24,7 @@ import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.plugins.Page;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.core.util.TenantUtils;
import com.pig4cloud.pigx.common.security.service.PigxUser;
import com.pig4cloud.pigx.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
@@ -152,7 +153,7 @@ public class PigxTokenEndpoint {
private boolean extractToken(Map<String, String> map, Object principal) {
if (principal instanceof PigxUser) {
PigxUser user = (PigxUser) principal;
if (!user.getTenantId().equals(SecurityUtils.getTenantId())) {
if (!user.getTenantId().equals(TenantUtils.getTenantId())) {
return true;
}
map.put("user_id", user.getId() + "");
+1 -1
View File
@@ -37,7 +37,7 @@
<!--工具类核心包 要从线程中获取租户ID-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pigx-common-security</artifactId>
<artifactId>pigx-common-core</artifactId>
<version>${pigx.version}</version>
</dependency>
<!--缓存依赖-->
@@ -18,7 +18,7 @@
package com.pig4cloud.pigx.common.cache;
import cn.hutool.core.util.StrUtil;
import com.pig4cloud.pigx.common.security.util.SecurityUtils;
import com.pig4cloud.pigx.common.core.util.TenantUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.data.redis.cache.RedisCache;
@@ -57,7 +57,7 @@ public class RedisAutoCacheManager extends RedisCacheManager {
if (cacheArray.length < 2) {
return super.createRedisCache(name, cacheConfig);
}
String cacheName = cacheArray[0] + ":" + SecurityUtils.getTenantId();
String cacheName = cacheArray[0] + ":" + TenantUtils.getTenantId();
if (cacheConfig != null) {
long cacheAge = Long.getLong(cacheArray[1], -1);
cacheConfig = cacheConfig.entryTtl(Duration.ofSeconds(cacheAge));
@@ -67,6 +67,6 @@ public class RedisAutoCacheManager extends RedisCacheManager {
@Override
public Cache getCache(String name) {
return super.getCache(name + ":" + SecurityUtils.getTenantId());
return super.getCache(name + ":" + TenantUtils.getTenantId());
}
}
+6
View File
@@ -77,5 +77,11 @@
<version>${jackson.modules}</version>
<type>pom</type>
</dependency>
<!--TTL-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>transmittable-thread-local</artifactId>
<version>${ttl.version}</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,49 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.common.core.util;
import com.alibaba.ttl.TransmittableThreadLocal;
/**
* @author lengleng
* @date 2018/10/4
* 租户工具类
*/
public class TenantUtils {
private static final ThreadLocal<Integer> THREAD_LOCAL_TENANT = new TransmittableThreadLocal<>();
/**
* TTL 设置租户ID
*
* @param tenantId
*/
public static void setTenantId(Integer tenantId) {
THREAD_LOCAL_TENANT.set(tenantId);
}
/**
* 获取TTL中的租户ID
*
* @return
*/
public static Integer getTenantId() {
return THREAD_LOCAL_TENANT.get();
}
}
-6
View File
@@ -51,11 +51,5 @@
<artifactId>pigx-upms-api</artifactId>
<version>${pigx.version}</version>
</dependency>
<!--TTL-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>transmittable-thread-local</artifactId>
<version>${ttl.version}</version>
</dependency>
</dependencies>
</project>
@@ -18,7 +18,7 @@
package com.pig4cloud.pigx.common.security.feign;
import com.pig4cloud.pigx.common.core.constant.CommonConstant;
import com.pig4cloud.pigx.common.security.util.SecurityUtils;
import com.pig4cloud.pigx.common.core.util.TenantUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
@@ -31,10 +31,10 @@ import lombok.extern.slf4j.Slf4j;
public class PigxFeignTenantInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
if (SecurityUtils.getTenantId() == null) {
if (TenantUtils.getTenantId() == null) {
log.error("TTL 中的 租户ID为空,feign拦截器 >> 增强失败");
return;
}
requestTemplate.header(CommonConstant.TENANT_ID, SecurityUtils.getTenantId().toString());
requestTemplate.header(CommonConstant.TENANT_ID, TenantUtils.getTenantId().toString());
}
}
@@ -19,7 +19,7 @@ package com.pig4cloud.pigx.common.security.filter;
import cn.hutool.core.util.StrUtil;
import com.pig4cloud.pigx.common.core.constant.CommonConstant;
import com.pig4cloud.pigx.common.security.util.SecurityUtils;
import com.pig4cloud.pigx.common.core.util.TenantUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
@@ -52,9 +52,9 @@ public class TenantIdTtlFilter extends GenericFilterBean {
log.debug("获取header中的租户ID为:{}", tenantId);
if (StrUtil.isNotBlank(tenantId)) {
SecurityUtils.setTenantId(Integer.parseInt(tenantId));
TenantUtils.setTenantId(Integer.parseInt(tenantId));
} else {
SecurityUtils.setTenantId(1);
TenantUtils.setTenantId(1);
}
filterChain.doFilter(request, response);
@@ -21,7 +21,6 @@ package com.pig4cloud.pigx.common.security.util;
import cn.hutool.core.util.StrUtil;
import com.alibaba.ttl.TransmittableThreadLocal;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.security.service.PigxUser;
import org.springframework.security.core.Authentication;
@@ -39,8 +38,6 @@ import java.util.List;
* @author L.cm
*/
public class SecurityUtils {
private static final ThreadLocal<Integer> THREAD_LOCAL_TENANT = new TransmittableThreadLocal<>();
/**
* 获取Authentication
*/
@@ -121,21 +118,4 @@ public class SecurityUtils {
return roleIds;
}
/**
* TTL 设置租户ID
*
* @param tenantId
*/
public static void setTenantId(Integer tenantId) {
THREAD_LOCAL_TENANT.set(tenantId);
}
/**
* 获取TTL中的租户ID
*
* @return
*/
public static Integer getTenantId() {
return THREAD_LOCAL_TENANT.get();
}
}
@@ -25,7 +25,7 @@ import com.baomidou.mybatisplus.plugins.parser.ISqlParser;
import com.baomidou.mybatisplus.plugins.parser.tenant.TenantHandler;
import com.baomidou.mybatisplus.plugins.parser.tenant.TenantSqlParser;
import com.pig4cloud.pigx.common.core.datascope.DataScopeInterceptor;
import com.pig4cloud.pigx.common.security.util.SecurityUtils;
import com.pig4cloud.pigx.common.core.util.TenantUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
@@ -59,8 +59,8 @@ public class MybatisPlusConfigurer {
tenantSqlParser.setTenantHandler(new TenantHandler() {
@Override
public Expression getTenantId() {
Integer tenantId = SecurityUtils.getTenantId();
log.error("当前租户为 >> {}", tenantId);
Integer tenantId = TenantUtils.getTenantId();
log.debug("当前租户为 >> {}", tenantId);
return new LongValue(tenantId);
}
@@ -71,7 +71,6 @@ public class MybatisPlusConfigurer {
@Override
public boolean doTableFilter(String tableName) {
log.error("当前租户表为 >> {}", tableName);
return ArrayUtil.contains(IGNORETABLES, tableName);
}
});
@@ -208,6 +208,10 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
SysUser sysUser = new SysUser();
BeanUtils.copyProperties(userDto, sysUser);
sysUser.setUpdateTime(LocalDateTime.now());
if (StrUtil.isNotBlank(userDto.getPassword())) {
sysUser.setPassword(ENCODER.encode(userDto.getPassword()));
}
this.updateById(sysUser);
SysUserRole condition = new SysUserRole();
@@ -20,7 +20,6 @@ package com.pig4cloud.pigx.act.controller;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pig4cloud.pigx.act.entity.LeaveBill;
import com.pig4cloud.pigx.act.service.ActTaskService;
import com.pig4cloud.pigx.act.service.LeaveBillService;
import com.pig4cloud.pigx.act.service.ProcessService;
import com.pig4cloud.pigx.common.core.constant.enums.EnumTaskStatus;
@@ -45,8 +44,6 @@ import java.util.Map;
public class LeaveBillController {
private final LeaveBillService leaveBillService;
private final ProcessService processService;
private final ActTaskService actTaskService;
/**
* 列表
@@ -17,14 +17,19 @@
package com.pig4cloud.pigx.act.controller;
import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.plugins.Page;
import com.pig4cloud.pigx.act.dto.ProcessDefDTO;
import com.pig4cloud.pigx.act.service.ProcessService;
import com.pig4cloud.pigx.common.core.constant.enums.EnumResourceType;
import com.pig4cloud.pigx.common.core.util.R;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Map;
@@ -44,22 +49,18 @@ public class ProcessController {
}
@GetMapping(value = "/resource/{proInsId}/{procDefId}/{resType}")
public void resourceRead(@PathVariable String procDefId, @PathVariable String proInsId, @PathVariable String resType, HttpServletResponse response) {
if ("xml".equals(resType)) {
response.setContentType("application/xml");
public ResponseEntity resourceRead(@PathVariable String procDefId, @PathVariable String proInsId, @PathVariable String resType) {
HttpHeaders headers = new HttpHeaders();
if (EnumResourceType.XML.getType().equals(resType)) {
headers.setContentType(MediaType.APPLICATION_XML);
} else {
response.setContentType("image/png");
headers.setContentType(MediaType.IMAGE_PNG);
}
try {
InputStream resourceAsStream = processService.resourceRead(procDefId, proInsId, resType);
byte[] b = new byte[1024];
int len = -1;
while ((len = resourceAsStream.read(b, 0, 1024)) != -1) {
response.getOutputStream().write(b, 0, len);
}
} catch (Exception e) {
}
InputStream resourceAsStream = processService.resourceRead(procDefId, proInsId, resType);
return new ResponseEntity(IoUtil.readBytes(resourceAsStream), headers, HttpStatus.CREATED);
}
@PutMapping("/status/{procDefId}/{status}")
@@ -17,16 +17,19 @@
package com.pig4cloud.pigx.act.controller;
import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.plugins.Page;
import com.pig4cloud.pigx.act.dto.LeaveBillDto;
import com.pig4cloud.pigx.act.service.ActTaskService;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
@@ -56,13 +59,11 @@ public class TaskController {
}
@GetMapping("/view/{id}")
public void viewCurrentImage(@PathVariable String id, HttpServletResponse resp) throws IOException {
public ResponseEntity viewCurrentImage(@PathVariable String id) {
InputStream imageStream = actTaskService.viewByTaskId(id);
byte[] b = new byte[1024];
int len;
while ((len = imageStream.read(b, 0, 1024)) != -1) {
resp.getOutputStream().write(b, 0, len);
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
return new ResponseEntity(IoUtil.readBytes(imageStream), headers, HttpStatus.CREATED);
}
@GetMapping("/comment/{id}")
@@ -52,11 +52,11 @@ public class LeaveProcessTaskListener implements TaskListener {
SecurityUtils.getUsername(), SecurityConstants.FROM_IN);
if (CollUtil.isEmpty(result.getData())) {
log.error("用户 {} 不存在上级,任务单由当前用户审批", SecurityUtils.getUsername());
log.debug("用户 {} 不存在上级,任务单由当前用户审批", SecurityUtils.getUsername());
delegateTask.addCandidateUser(SecurityUtils.getUsername());
} else {
List<String> userList = result.getData().stream().map(SysUser::getUsername).collect(Collectors.toList());
log.error("当前任务 {},由 {}处理", delegateTask.getId(), userList);
log.debug("当前任务 {},由 {}处理", delegateTask.getId(), userList);
delegateTask.addCandidateUsers(userList);
}
@@ -101,26 +101,20 @@ public class ActTaskServiceImpl implements ActTaskService {
*/
@Override
public LeaveBillDto findTaskByTaskId(String taskId) {
//1:使用任务ID,查询任务对象Task
Task task = taskService.createTaskQuery()
.taskId(taskId)
.singleResult();
//2:使用任务对象Task获取流程实例ID
String processInstanceId = task.getProcessInstanceId();
//3:使用流程实例ID,查询正在执行的执行对象表,返回流程实例对象
ProcessInstance pi = runtimeService.createProcessInstanceQuery()
.processInstanceId(processInstanceId)
.processInstanceId(task.getProcessInstanceId())
.singleResult();
//4:使用流程实例对象获取BUSINESS_KEY
String businessKey = pi.getBusinessKey();
//5:获取BUSINESS_KEY对应的主键ID,使用主键ID,查询请假单对象(LeaveBill.1)
if (StrUtil.isNotBlank(businessKey)) {
//截取字符串,取buniness_key小数点的第2个值
businessKey = businessKey.split("_")[1];
}
List<String> comeList = findOutFlagListByTaskId(task, pi);
//查询请假单对象
LeaveBill leaveBill = leaveBillMapper.selectById(businessKey);
LeaveBillDto leaveBillDto = new LeaveBillDto();
@@ -139,20 +133,15 @@ public class ActTaskServiceImpl implements ActTaskService {
*/
@Override
public Boolean submitTask(LeaveBillDto leaveBillDto) {
//获取任务ID
String taskId = leaveBillDto.getTaskId();
//批注信息
String message = leaveBillDto.getComment();
//获取请假单ID
Integer id = leaveBillDto.getLeaveId();
//添加一个批注信息,向act_hi_comment表中添加数据,用于记录对当前申请人的一些审核信息
Task task = taskService.createTaskQuery()
.taskId(taskId)
.singleResult();
//获取流程实例ID
String processInstanceId = task.getProcessInstanceId();
// 设置批注用户
String processInstanceId = task.getProcessInstanceId();
Authentication.setAuthenticatedUserId(SecurityUtils.getUsername());
taskService.addComment(taskId, processInstanceId, message);
@@ -161,14 +150,12 @@ public class ActTaskServiceImpl implements ActTaskService {
if (!StrUtil.equals(FLAG, leaveBillDto.getTaskFlag())) {
variables.put("flag", leaveBillDto.getTaskFlag());
}
//使用任务ID,完成当前人的个人任务
taskService.complete(taskId, variables);
//在完成任务之后,判断流程是否结束
taskService.complete(taskId, variables);
ProcessInstance pi = runtimeService.createProcessInstanceQuery()
.processInstanceId(processInstanceId)
.singleResult();
//流程结束了
if (pi == null) {
LeaveBill bill = new LeaveBill();
bill.setLeaveId(id);
@@ -21,18 +21,16 @@ import cn.hutool.core.util.CharsetUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.pig4cloud.pigx.act.service.EditorService;
import com.pig4cloud.pigx.common.security.util.SecurityUtils;
import com.pig4cloud.pigx.common.core.util.TenantUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Model;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
@@ -42,6 +40,7 @@ import static org.activiti.editor.constants.ModelDataJsonConstants.*;
* @author lengleng
* @date 2018/9/25
*/
@Slf4j
@Service
@AllArgsConstructor
public class EditorServiceImpl implements EditorService {
@@ -57,8 +56,9 @@ public class EditorServiceImpl implements EditorService {
public Object getStencilset() {
InputStream stencilsetStream = this.getClass().getClassLoader().getResourceAsStream("stencilset.json");
try {
return IOUtils.toString(stencilsetStream, "utf-8");
return IOUtils.toString(stencilsetStream, CharsetUtil.UTF_8);
} catch (Exception e) {
log.error("Error while loading stencil set", e);
throw new ActivitiException("Error while loading stencil set", e);
}
}
@@ -71,7 +71,7 @@ public class EditorServiceImpl implements EditorService {
*/
@Override
public Object getEditorJson(String modelId) {
ObjectNode modelNode = null;
ObjectNode modelNode;
Model model = repositoryService.getModel(modelId);
if (model != null) {
try {
@@ -83,10 +83,11 @@ public class EditorServiceImpl implements EditorService {
}
byte[] source = repositoryService.getModelEditorSource(model.getId());
modelNode.put(MODEL_ID, model.getId());
ObjectNode editorJsonNode = (ObjectNode) objectMapper.readTree(new String(source, "utf-8"));
ObjectNode editorJsonNode = (ObjectNode) objectMapper.readTree(new String(source, CharsetUtil.UTF_8));
modelNode.set("model", editorJsonNode);
return modelNode;
} catch (Exception e) {
log.error("Error creating model JSON", e);
throw new ActivitiException("Error creating model JSON", e);
}
}
@@ -111,8 +112,8 @@ public class EditorServiceImpl implements EditorService {
modelJson.put(MODEL_DESCRIPTION, description);
model.setMetaInfo(modelJson.toString());
model.setName(name);
model.setTenantId(String.valueOf(SecurityUtils.getTenantId()));
model.setTenantId(String.valueOf(TenantUtils.getTenantId()));
repositoryService.saveModel(model);
repositoryService.addModelEditorSource(model.getId(), jsonXml.getBytes(CharsetUtil.UTF_8));
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
@@ -120,6 +121,7 @@ public class EditorServiceImpl implements EditorService {
repositoryService.addModelEditorSourceExtra(model.getId(), result);
outStream.close();
} catch (Exception e) {
log.error("Error saving model", e);
throw new ActivitiException("Error saving model", e);
}
}
@@ -24,7 +24,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.pig4cloud.pigx.act.service.ModelService;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.security.util.SecurityUtils;
import com.pig4cloud.pigx.common.core.util.TenantUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.model.BpmnModel;
@@ -88,12 +88,13 @@ public class ModelServiceImpl implements ModelService {
modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, model.getVersion());
modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, desc);
model.setMetaInfo(modelObjectNode.toString());
model.setTenantId(String.valueOf(SecurityUtils.getTenantId()));
model.setTenantId(String.valueOf(TenantUtils.getTenantId()));
repositoryService.saveModel(model);
repositoryService.addModelEditorSource(model.getId(), editorNode.toString().getBytes("utf-8"));
return model;
} catch (UnsupportedEncodingException e) {
log.error("UnsupportedEncodingException", e);
}
return null;
}
@@ -156,7 +157,7 @@ public class ModelServiceImpl implements ModelService {
Deployment deployment = repositoryService
.createDeployment().name(model.getName())
.addBpmnModel(processName, bpmnModel)
.tenantId(String.valueOf(SecurityUtils.getTenantId()))
.tenantId(String.valueOf(TenantUtils.getTenantId()))
.deploy();
// 设置流程分类
@@ -27,7 +27,7 @@ import com.pig4cloud.pigx.act.service.ProcessService;
import com.pig4cloud.pigx.common.core.constant.enums.EnumProcessStatus;
import com.pig4cloud.pigx.common.core.constant.enums.EnumResourceType;
import com.pig4cloud.pigx.common.core.constant.enums.EnumTaskStatus;
import com.pig4cloud.pigx.common.security.util.SecurityUtils;
import com.pig4cloud.pigx.common.core.util.TenantUtils;
import lombok.AllArgsConstructor;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
@@ -157,15 +157,12 @@ public class ProcessServiceImpl implements ProcessService {
*/
@Override
public Boolean saveStartProcess(Integer leaveId) {
//1:获取请假单ID,使用请假单ID,查询请假单的对象LeaveBill
LeaveBill leaveBill = leaveBillMapper.selectById(leaveId);
leaveBill.setState(EnumTaskStatus.CHECK.getStatus());
//2:使用当前对象获取到流程定义的key(对象的名称就是流程定义的key)
String key = leaveBill.getClass().getSimpleName();
//3: 格式:LeaveBill_id的形式(使用流程变量)
String businessKey = key + "_" + leaveBill.getLeaveId();
//4:使用流程定义的key,启动流程实例,正在执行的执行对象表中的字段BUSINESS_KEY添加业务数据,同时让流程关联业务
runtimeService.startProcessInstanceByKeyAndTenantId(key, businessKey, String.valueOf(SecurityUtils.getTenantId()));
runtimeService.startProcessInstanceByKeyAndTenantId(key, businessKey, String.valueOf(TenantUtils.getTenantId()));
leaveBillMapper.updateById(leaveBill);
return Boolean.TRUE;
}