自定义注解配合aop

2020-12-23  本文已影响0人  有趣有趣

首先创建一个自定义注解,此注解使用在流程抄送的service方法上

import java.lang.annotation.*;

/**

* 流程需要抄送的功能

*/

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

public @interface FuncCCAnnotation {

String desc() default "";

    String funcId() default "";

}

使用时只需要在方法上注解

/**

* 完成任务

*

* @param baseProcessForm 流程任务表单

* @return string

*/

@Override

@Transactional(rollbackFor = RuntimeException.class)

@FuncCCAnnotation(desc ="通过", funcId ="5")

public StringcompleteTask(BaseProcessForm baseProcessForm) {

//具体省略

}

最后创建aop

import java.lang.reflect.Method;

import java.util.*;

import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import javax.validation.constraints.NotNull;

import cn.hutool.core.collection.CollUtil;

import com.alibaba.fastjson.JSONArray;

import com.alibaba.fastjson.JSONObject;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;

import com.sx.common.exception.SxException;

import com.sx.common.util.ServletUtil;

import com.sx.gov.express.annotation.FuncCCAnnotation;

import com.sx.gov.express.entity.SxFlowCc;

import com.sx.gov.express.form.BaseProcessForm;

import com.sx.gov.express.service.SxFlowCcService;

import com.sx.smart.form.util.DbUtils;

import com.sx.system.constants.SystemCommonConstants;

import com.sx.system.mapper.SysUserMapper;

import com.sx.system.uitl.UserUtil;

import com.sx.work.flow.exceptionhandler.FlowExceptionEnum;

import com.sx.work.flow.mapper.FlowIdentityMapper;

import org.apache.commons.lang3.ArrayUtils;

import org.apache.commons.lang3.StringUtils;

import org.aspectj.lang.JoinPoint;

import org.aspectj.lang.ProceedingJoinPoint;

import org.aspectj.lang.Signature;

import org.aspectj.lang.annotation.*;

import org.aspectj.lang.reflect.MethodSignature;

import org.flowable.bpmn.model.*;

import org.flowable.engine.RepositoryService;

import org.flowable.engine.TaskService;

import org.flowable.task.api.Task;

import org.flowable.task.service.impl.persistence.entity.TaskEntity;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

import org.springframework.web.context.request.RequestContextHolder;

import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect

@Component

public class FuncCcAop {

@Autowired

    private TaskServicetaskService;

    @Autowired

    private RepositoryServicerepositoryService;

    @Autowired

    private FlowIdentityMapperflowIdentityMapper;

    @Autowired

    private SysUserMapperuserMapper;

    @Autowired

    private SxFlowCcServicesxFlowCcService;

    /**

    * 切面

    */

    @Pointcut("@annotation(com.sx.gov.express.annotation.FuncCCAnnotation)")

public void insertCC() {

}

/**

    * 环绕操作

    *

    * @param point 切入点

    * @return 原方法返回值

    * @throws Throwable 异常信息

    */

    @Around("insertCC()")

public Object aroundLog(@NotNull ProceedingJoinPoint point)throws Throwable {

String methodName = point.getSignature().getName();

        String declaringTypeName = point.getSignature().getDeclaringTypeName();

        Signature signature = point.getSignature();

        MethodSignature methodSignature = (MethodSignature) signature;

        Method method = methodSignature.getMethod();

        Object[] paramValues = point.getArgs();

//        String[] paramNames = ((MethodSignature) point.getSignature()).getParameterNames();

        BaseProcessForm baseProcessForm = (BaseProcessForm) paramValues[0];

        String flowTaskId = baseProcessForm.getFlowTaskId();

        Task task =taskService.createTaskQuery().includeProcessVariables().taskId(flowTaskId).singleResult();

        BpmnModel bpmnModel =repositoryService.getBpmnModel(task.getProcessDefinitionId());

        FlowNode flowNode = (FlowNode) bpmnModel.getFlowElement(task.getTaskDefinitionKey());

        // 查找当前节点的用户配置

        Map> extensionElements = flowNode.getExtensionElements();

        List ccCustom = extensionElements.get("ccCustom");

        if (ccCustom !=null) {

FuncCCAnnotation funcCCAnnotation = method.getAnnotation(FuncCCAnnotation.class);

            String action = funcCCAnnotation.desc();

            String funcId = funcCCAnnotation.funcId();

            ExtensionAttribute ccFuncId = ccCustom.get(0).getAttributes().get("funcId").get(0);

            String[] ccFuncIds = ccFuncId.getValue().split(",");

            if (ArrayUtils.contains(ccFuncIds, funcId)) {

String itemCode = (String) task.getProcessVariables().get("itemCode");

                String taskCode = (String) task.getProcessVariables().get("taskCode");

                String itemName = DbUtils.getItemByCode(itemCode).getItemName();

                String userTaskId = task.getTaskDefinitionKey();

                String userTaskName = task.getName();

                String createUserName = UserUtil.getUser().getUserName();

                Set userSet = userTaskVariables(ccCustom, itemCode, taskCode);

                List sxFlowCcList = userSet.stream().map(uid -> {

SxFlowCc sxFlowCc =new SxFlowCc();

                    sxFlowCc.setItemCode(itemCode);

                    sxFlowCc.setTaskCode(taskCode);

                    sxFlowCc.setItemName(itemName);

                    sxFlowCc.setAction(action);

                    sxFlowCc.setUserTaskId(userTaskId);

                    sxFlowCc.setUserTaskName(userTaskName);

                    sxFlowCc.setCcUserId(Integer.parseInt(uid));

                    sxFlowCc.setCcUserName(UserUtil.getUserInfo(uid).getUserName());

                    sxFlowCc.setCreateUserName(createUserName);

                    return sxFlowCc;

                }).collect(Collectors.toList());

                if (CollUtil.isNotEmpty(userSet)) {

sxFlowCcService.saveBatch(sxFlowCcList);

                }

}

}

return point.proceed();

    }

/**

    * 具体处理用户信息

    *

    * @param ccCustom

    * @return Set

*/

    private SetuserTaskVariables(List ccCustom, String itemCode, String taskCode) {

Set assigneeSet =new HashSet<>();

        Map valueMap =null;

        // 人员处理--直接设置用户uid

        boolean userFlag = ccCustom.get(0).getAttributes().get("userFlag") !=null;

        boolean roleFlag = ccCustom.get(0).getAttributes().get("roleFlag") !=null;

        boolean orgFlag = ccCustom.get(0).getAttributes().get("orgFlag") !=null;

        if (userFlag) {

Map> childElements = ccCustom.get(0).getChildElements();

            Map> user = childElements.get("user").get(0).getAttributes();

            String formField = user.get("formField").get(0).getValue();

            List uid = Arrays.asList(user.get("uid").get(0).getValue().split(","));

            if ("1".equals(formField)) {

//指定人员

                assigneeSet.addAll(uid);

            }else if ("2".equals(formField)) {

//从表单中获取录入的人员信息

                valueMap = DbUtils.getValMapByItem(itemCode, taskCode);

                Map finalValueMap = valueMap;

                List collectIds = uid.stream().map(id -> String.valueOf(finalValueMap.get(id))).collect(Collectors.toList());

                collectIds.forEach(collectId -> {

assigneeSet.addAll(Arrays.stream(collectId.split(",")).collect(Collectors.toList()));

                });

            }

}

// 角色处理--查找到角色相对应的uid

        if (roleFlag) {

Set assigneeRolSet =new HashSet<>();

            Map> childElements = ccCustom.get(0).getChildElements();

            List roleIds = Arrays.asList(

childElements.get("role").get(0).getAttributes().get("roleId").get(0).getValue().split(","));

            Set uids =flowIdentityMapper.selectUidByRoleIds(roleIds);

            assigneeRolSet.addAll(uids);

            if (userFlag) {

//如果配置了人员信息,则取交集

                assigneeSet.retainAll(assigneeRolSet);

            }else {

assigneeSet.addAll(assigneeRolSet);

            }

}

// 部门机构处理--查找到部门相对应的uid

        if (orgFlag) {

Set assigneeOrgSet =new HashSet<>();

            Map> childElements = ccCustom.get(0).getChildElements();

            Map> org = childElements.get("org").get(0).getAttributes();

            String formField = org.get("formField").get(0).getValue();

            List orgIds = Arrays.asList(org.get("orgId").get(0).getValue().split(","));

            if ("2".equals(formField)) {

//"2"表示从表单字段中获取机构信息

                valueMap = valueMap ==null ? DbUtils.getValMapByItem(itemCode, taskCode) : valueMap;

                Map finalValueMap1 = valueMap;

                List orgs =new ArrayList<>();

                orgIds.forEach(orgId -> {

//拿到字段对应的值 格式为[{"name":"市场监督管理局","value":"438"}]

                    String values = String.valueOf(finalValueMap1.get(orgId));

                    //从机构信息中获取机构id

                    JSONArray objects = JSONArray.parseArray(values);

                    for (Object object : objects) {

JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(object));

                        String value = jsonObject.getString("value");

                        orgs.add(value);

                    }

});

                orgIds = orgs;

            }

Set uids =flowIdentityMapper.selectUidByOrgIds(orgIds);

            assigneeOrgSet.addAll(uids);

            if (userFlag || roleFlag) {

//如果配置了人员信息或者权限标识,则取交集

                assigneeSet.retainAll(assigneeOrgSet);

            }else {

assigneeSet.addAll(assigneeOrgSet);

            }

}

return assigneeSet;

    }

}

以上为核心代码

上一篇下一篇

猜你喜欢

热点阅读