Browse Source

优化定时调度

zhouhao 7 years ago
parent
commit
4c3975f200
15 changed files with 196 additions and 98 deletions
  1. 5 0
      hsweb-examples/hsweb-examples-simple/pom.xml
  2. 11 1
      hsweb-examples/hsweb-examples-simple/src/main/java/org/hswebframework/web/example/simple/SpringBootExample.java
  3. 15 0
      hsweb-examples/hsweb-examples-workflow/pom.xml
  4. 1 0
      hsweb-examples/pom.xml
  5. 22 2
      hsweb-system/hsweb-system-schedule/hsweb-system-schedule-controller/src/main/java/org/hswebframework/web/controller/schedule/ScheduleJobController.java
  6. 1 1
      hsweb-system/hsweb-system-schedule/hsweb-system-schedule-service/hsweb-system-schedule-service-simple/src/main/java/org/hswebframework/web/service/schedule/simple/DefaultScriptScheduleJobExecutor.java
  7. 13 3
      hsweb-system/hsweb-system-schedule/hsweb-system-schedule-service/hsweb-system-schedule-service-simple/src/main/java/org/hswebframework/web/service/schedule/simple/SimpleScheduleJobService.java
  8. 23 5
      hsweb-system/hsweb-system-schedule/hsweb-system-schedule-starter/src/test/java/org/hswebframework/web/schedule/test/DynamicScheduleTests.java
  9. 21 0
      hsweb-system/hsweb-system-schedule/hsweb-system-schedule-starter/src/test/resources/application.yml
  10. 6 1
      hsweb-system/hsweb-system-workflow/hsweb-system-workflow-flowable/pom.xml
  11. 1 5
      hsweb-system/hsweb-system-workflow/hsweb-system-workflow-flowable/src/main/java/org/hswebframework/web/workflow/flowable/controller/FlowableDeploymentController.java
  12. 6 6
      hsweb-system/hsweb-system-workflow/hsweb-system-workflow-flowable/src/main/java/org/hswebframework/web/workflow/flowable/entity/TaskInfo.java
  13. 15 17
      hsweb-system/hsweb-system-workflow/hsweb-system-workflow-flowable/src/main/java/org/hswebframework/web/workflow/flowable/service/imp/BpmProcessServiceImp.java
  14. 54 53
      hsweb-system/hsweb-system-workflow/hsweb-system-workflow-flowable/src/main/java/org/hswebframework/web/workflow/flowable/service/imp/BpmTaskServiceImp.java
  15. 2 4
      hsweb-system/hsweb-system-workflow/hsweb-system-workflow-flowable/src/main/java/org/hswebframework/web/workflow/flowable/utils/FlowableAbstract.java

+ 5 - 0
hsweb-examples/hsweb-examples-simple/pom.xml

@@ -134,6 +134,11 @@
             <version>${project.version}</version>
         </dependency>
 
+        <dependency>
+            <groupId>org.hswebframework.web</groupId>
+            <artifactId>hsweb-system-schedule-starter</artifactId>
+            <version>${project.version}</version>
+        </dependency>
         <!--动态表单-->
         <dependency>
             <groupId>org.hswebframework.web</groupId>

+ 11 - 1
hsweb-examples/hsweb-examples-simple/src/main/java/org/hswebframework/web/example/simple/SpringBootExample.java

@@ -22,9 +22,13 @@ import com.alibaba.fastjson.serializer.SerializerFeature;
 import org.hswebframework.web.authorization.Authentication;
 import org.hswebframework.web.authorization.Permission;
 import org.hswebframework.web.authorization.access.DataAccessConfig;
+import org.hswebframework.web.authorization.basic.aop.AopMethodAuthorizeDefinitionCustomizerParser;
 import org.hswebframework.web.authorization.basic.configuration.EnableAopAuthorize;
+import org.hswebframework.web.authorization.basic.define.EmptyAuthorizeDefinition;
 import org.hswebframework.web.authorization.basic.web.UserTokenHolder;
+import org.hswebframework.web.authorization.define.AuthorizeDefinition;
 import org.hswebframework.web.authorization.simple.SimpleFieldFilterDataAccessConfig;
+import org.hswebframework.web.boost.aop.context.MethodInterceptorContext;
 import org.hswebframework.web.commons.entity.DataStatus;
 import org.hswebframework.web.commons.entity.factory.EntityFactory;
 import org.hswebframework.web.entity.authorization.*;
@@ -84,6 +88,12 @@ import java.util.stream.Stream;
 public class SpringBootExample
         implements CommandLineRunner {
 
+    @Bean
+    public AopMethodAuthorizeDefinitionCustomizerParser customizerParser(){
+        //自定义权限声明
+        return context -> EmptyAuthorizeDefinition.instance;
+    }
+
     @Bean
     public AccessLoggerListener accessLoggerListener() {
         Class excludes[] = {
@@ -100,7 +110,7 @@ public class SpringBootExample
                     return obj.getClass().getName();
                 return JSON.toJSONString(obj);
             });
-            loggerMap.put("userToken", UserTokenHolder.currentToken());
+//            loggerMap.put("userToken", UserTokenHolder.currentToken());
 
             System.out.println(JSON.toJSONString(loggerMap, SerializerFeature.SortField, SerializerFeature.PrettyFormat));
 

+ 15 - 0
hsweb-examples/hsweb-examples-workflow/pom.xml

@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <parent>
+        <artifactId>hsweb-examples</artifactId>
+        <groupId>org.hswebframework.web</groupId>
+        <version>3.0-SNAPSHOT</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+
+    <artifactId>hsweb-examples-workflow</artifactId>
+
+
+</project>

+ 1 - 0
hsweb-examples/pom.xml

@@ -32,6 +32,7 @@
         <module>hsweb-examples-simple</module>
         <module>hsweb-examples-oauth2</module>
         <module>hsweb-examples-custom-entity</module>
+        <module>hsweb-examples-workflow</module>
     </modules>
 
     <build>

+ 22 - 2
hsweb-system/hsweb-system-schedule/hsweb-system-schedule-controller/src/main/java/org/hswebframework/web/controller/schedule/ScheduleJobController.java

@@ -1,12 +1,16 @@
 package org.hswebframework.web.controller.schedule;
 
+import org.hswebframework.web.authorization.Permission;
 import org.hswebframework.web.authorization.annotation.Authorize;
 import org.hswebframework.web.commons.entity.param.QueryParamEntity;
 import org.hswebframework.web.controller.SimpleGenericEntityController;
+import org.hswebframework.web.controller.message.ResponseMessage;
 import org.hswebframework.web.entity.schedule.ScheduleJobEntity;
 import org.hswebframework.web.logging.AccessLogger;
 import  org.hswebframework.web.service.schedule.ScheduleJobService;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PutMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 
@@ -16,8 +20,8 @@ import org.springframework.web.bind.annotation.RestController;
  * @author hsweb-generator-online
  */
 @RestController
-@RequestMapping("${hsweb.web.mappings.scheduleJob:scheduleJob}")
-@Authorize(permission = "scheduleJob")
+@RequestMapping("${hsweb.web.mappings.scheduleJob:schedule/job}")
+@Authorize(permission = "schedule-job")
 @AccessLogger("调度任务")
 public class ScheduleJobController implements SimpleGenericEntityController<ScheduleJobEntity, String, QueryParamEntity> {
 
@@ -32,4 +36,20 @@ public class ScheduleJobController implements SimpleGenericEntityController<Sche
     public ScheduleJobService getService() {
         return scheduleJobService;
     }
+
+    @PutMapping("/{id}/enable")
+    @Authorize(action = Permission.ACTION_ENABLE)
+    @AccessLogger("启用")
+    public ResponseMessage<Void> enable(@PathVariable String id){
+        scheduleJobService.enable(id);
+        return ResponseMessage.ok();
+    }
+
+    @PutMapping("/{id}/disable")
+    @Authorize(action = Permission.ACTION_DISABLE)
+    @AccessLogger("禁用")
+    public ResponseMessage<Void> disable(@PathVariable String id){
+        scheduleJobService.disable(id);
+        return ResponseMessage.ok();
+    }
 }

+ 1 - 1
hsweb-system/hsweb-system-schedule/hsweb-system-schedule-service/hsweb-system-schedule-service-simple/src/main/java/org/hswebframework/web/service/schedule/simple/DefaultScriptScheduleJobExecutor.java

@@ -35,7 +35,7 @@ public class DefaultScriptScheduleJobExecutor implements ScheduleJobExecutor {
 
             String jobMd5 = DigestUtils.md5Hex(jobEntity.getScript());
             //脚本发生变化,重新编译执行
-            if (!jobMd5.equals(engine.getContext(jobId).getMd5())) {
+            if (engine.getContext(jobId)==null||!jobMd5.equals(engine.getContext(jobId).getMd5())) {
                 engine.compile(jobId, jobEntity.getScript());
             }
             return engine.execute(jobId, parameter).getIfSuccess();

+ 13 - 3
hsweb-system/hsweb-system-schedule/hsweb-system-schedule-service/hsweb-system-schedule-service-simple/src/main/java/org/hswebframework/web/service/schedule/simple/SimpleScheduleJobService.java

@@ -8,6 +8,7 @@ import org.hswebframework.web.commons.entity.DataStatus;
 import org.hswebframework.web.dao.schedule.ScheduleJobDao;
 import org.hswebframework.web.entity.schedule.ScheduleJobEntity;
 import org.hswebframework.web.id.IDGenerator;
+import org.hswebframework.web.service.EnableCacheGenericEntityService;
 import org.hswebframework.web.service.GenericEntityService;
 import org.hswebframework.web.service.schedule.ScheduleJobService;
 import org.hswebframework.web.service.schedule.ScheduleTriggerBuilder;
@@ -15,12 +16,14 @@ import org.quartz.*;
 import org.quartz.spi.MutableTrigger;
 import org.quartz.spi.OperableTrigger;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.cache.annotation.CacheConfig;
 import org.springframework.stereotype.Service;
 import org.springframework.util.StringUtils;
 
 import java.util.Date;
 import java.util.LinkedList;
 import java.util.List;
+import java.util.Objects;
 
 /**
  * 默认的服务实现
@@ -28,6 +31,7 @@ import java.util.List;
  * @author hsweb-generator-online
  */
 @Service("scheduleJobService")
+//@CacheConfig(cacheNames = "schedule-job")
 public class SimpleScheduleJobService extends GenericEntityService<ScheduleJobEntity, String>
         implements ScheduleJobService {
     @Autowired
@@ -78,6 +82,8 @@ public class SimpleScheduleJobService extends GenericEntityService<ScheduleJobEn
     }
 
     protected void startJob(ScheduleJobEntity jobEntity) {
+        try {
+        if(scheduler.checkExists(createJobKey(jobEntity)))return;
         JobDetail jobDetail = JobBuilder
                 .newJob(DynamicJob.class)
                 .withIdentity(createJobKey(jobEntity))
@@ -87,7 +93,7 @@ public class SimpleScheduleJobService extends GenericEntityService<ScheduleJobEn
                 .build();
         MutableTrigger trigger = scheduleTriggerBuilder.buildTrigger(jobEntity.getQuartzConfig());
         trigger.setKey(createTriggerKey(jobEntity));
-        try {
+
             scheduler.scheduleJob(jobDetail, trigger);
         } catch (SchedulerException e) {
             throw new BusinessException("启动定时调度失败", e);
@@ -120,8 +126,10 @@ public class SimpleScheduleJobService extends GenericEntityService<ScheduleJobEn
 
     @Override
     public void enable(String id) {
-        createUpdate().set(ScheduleJobEntity.status, DataStatus.STATUS_ENABLED)
+        Objects.requireNonNull(id);
+      int size=  createUpdate().set(ScheduleJobEntity.status, DataStatus.STATUS_ENABLED)
                 .where(ScheduleJobEntity.id, id).exec();
+      if(size>0)
         startJob(selectByPk(id));
     }
 
@@ -138,8 +146,10 @@ public class SimpleScheduleJobService extends GenericEntityService<ScheduleJobEn
 
     @Override
     public void disable(String id) {
-        createUpdate().set(ScheduleJobEntity.status, DataStatus.STATUS_DISABLED)
+        Objects.requireNonNull(id);
+       int size =  createUpdate().set(ScheduleJobEntity.status, DataStatus.STATUS_DISABLED)
                 .where(ScheduleJobEntity.id, id).exec();
+       if(size>0)
         deleteJob(selectByPk(id));
     }
 }

+ 23 - 5
hsweb-system/hsweb-system-schedule/hsweb-system-schedule-starter/src/test/java/org/hswebframework/web/schedule/test/DynamicScheduleTests.java

@@ -4,36 +4,54 @@ import org.hswebframework.web.commons.entity.DataStatus;
 import org.hswebframework.web.entity.schedule.ScheduleJobEntity;
 import org.hswebframework.web.service.schedule.ScheduleJobService;
 import org.hswebframework.web.tests.SimpleWebApplicationTests;
+import org.junit.Assert;
+import org.junit.Before;
 import org.junit.Test;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.util.concurrent.atomic.AtomicLong;
 
 /**
  * TODO 完成注释
  *
  * @author zhouhao
  */
+@Transactional(propagation = Propagation.NOT_SUPPORTED)
 public class DynamicScheduleTests extends SimpleWebApplicationTests {
 
     @Autowired
     private ScheduleJobService scheduleJobService;
 
 
+    public static final AtomicLong counter=new AtomicLong();
+    private String id;
+
+    @Before
+    public void initJob() throws InterruptedException {
+        Thread.sleep(5000);
+        id = scheduleJobService.insert(createJob());
+        scheduleJobService.enable(id);
+    }
+
     public ScheduleJobEntity createJob() {
         ScheduleJobEntity entity = scheduleJobService.createEntity();
         entity.setStatus(DataStatus.STATUS_ENABLED);
         entity.setType("test");
         entity.setLanguage("javascript");
-        entity.setScript("java.lang.System.out.println('job running...')");
+        entity.setScript("" +
+                "org.hswebframework.web.schedule.test.DynamicScheduleTests.counter.incrementAndGet()\n" +
+                "java.lang.System.out.println('job running...')");
         entity.setQuartzConfig("{\"type\":\"cron\",\"config\":\"0/5 * * * * ?\"}");
         return entity;
     }
 
     @Test
     public void testCreateJob() throws InterruptedException {
-        Thread.sleep(5000);
-        String id = scheduleJobService.insert(createJob());
-        scheduleJobService.enable(id);
 
-        Thread.sleep(40000);
+
+        Thread.sleep(10000);
+        Assert.assertTrue(counter.get()>0);
     }
 }

+ 21 - 0
hsweb-system/hsweb-system-schedule/hsweb-system-schedule-starter/src/test/resources/application.yml

@@ -0,0 +1,21 @@
+spring:
+    aop:
+        auto: true
+        proxy-target-class: true
+    datasource:
+       url : jdbc:h2:file:./target/workflow-test
+       username : sa
+       password :
+       type: com.alibaba.druid.pool.DruidDataSource
+       driver-class-name : org.h2.Driver
+    cache:
+       type: simple
+
+logging:
+  level:
+        org.quartz: debug
+#      org.activiti: debug
+mybatis:
+  dynamic-datasource: false
+server:
+  port: 8080

+ 6 - 1
hsweb-system/hsweb-system-workflow/hsweb-system-workflow-flowable/pom.xml

@@ -134,7 +134,12 @@
         <dependency>
             <groupId>org.hswebframework.web</groupId>
             <artifactId>hsweb-tests</artifactId>
-            <version>3.0-SNAPSHOT</version>
+            <version>${project.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.hswebframework.web</groupId>
+            <artifactId>hsweb-system-dynamic-form-service-api</artifactId>
+            <version>${project.version}</version>
         </dependency>
     </dependencies>
 </project>

+ 1 - 5
hsweb-system/hsweb-system-workflow/hsweb-system-workflow-flowable/src/main/java/org/hswebframework/web/workflow/flowable/controller/FlowableDeploymentController.java

@@ -111,11 +111,10 @@ public class FlowableDeploymentController extends FlowableAbstract {
      * 加载ZIP文件中的流程
      */
     @PostMapping(value = "/deploy")
-    public ResponseMessage<Object> deploy(@RequestParam(value = "file") MultipartFile file) {
+    public ResponseMessage<Object> deploy(@RequestParam(value = "file") MultipartFile file) throws IOException {
         // 获取上传的文件名
         String fileName = file.getOriginalFilename();
 
-        try {
             // 得到输入流(字节流)对象
             InputStream fileInputStream = file.getInputStream();
 
@@ -132,9 +131,6 @@ public class FlowableDeploymentController extends FlowableAbstract {
                 deployment.addInputStream(fileName, fileInputStream);
             }
             deployment.deploy();
-        } catch (Exception e) {
-//            logger.error("部署流程错误,获取文件流失败");
-        }
 
         return ResponseMessage.ok();
     }

+ 6 - 6
hsweb-system/hsweb-system-workflow/hsweb-system-workflow-flowable/src/main/java/org/hswebframework/web/workflow/flowable/entity/TaskInfo.java

@@ -29,7 +29,7 @@ public class TaskInfo extends SimpleGenericEntity<String> {
 
     private Object mainFormData;
 
-    private String pid;
+    private String parentId;
 
     private String processInstanceId;
 
@@ -59,12 +59,12 @@ public class TaskInfo extends SimpleGenericEntity<String> {
         this.definition = definition;
     }
 
-    public String getPid() {
-        return pid;
+    public String getParentId() {
+        return parentId;
     }
 
-    public void setPid(String pid) {
-        this.pid = pid;
+    public void setParentId(String parentId) {
+        this.parentId = parentId;
     }
 
     public String getType() {
@@ -88,7 +88,7 @@ public class TaskInfo extends SimpleGenericEntity<String> {
         this.setName(task.getName());
         this.setCreateDate(task.getCreateTime());
         this.setProcessInstanceId(task.getProcessInstanceId());
-        this.setPid(task.getParentTaskId());
+        this.setParentId(task.getParentTaskId());
         Map<String, Object> var = task.getProcessVariables();
         this.setFormId((String) var.get("mainFormId"));
         this.setDataId((String) var.get("mainFormDataId"));

+ 15 - 17
hsweb-system/hsweb-system-workflow/hsweb-system-workflow-flowable/src/main/java/org/hswebframework/web/workflow/flowable/service/imp/BpmProcessServiceImp.java

@@ -1,14 +1,8 @@
 package org.hswebframework.web.workflow.flowable.service.imp;
 
-import org.activiti.engine.impl.RepositoryServiceImpl;
-import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
-import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
-import org.activiti.engine.impl.pvm.process.ActivityImpl;
-import org.activiti.engine.impl.pvm.process.ProcessDefinitionImpl;
 import org.activiti.engine.repository.ProcessDefinition;
 import org.activiti.engine.runtime.Job;
 import org.activiti.engine.runtime.ProcessInstance;
-import org.activiti.engine.runtime.ProcessInstanceQuery;
 import org.activiti.engine.task.Task;
 import org.hswebframework.utils.StringUtils;
 import org.hswebframework.web.workflow.flowable.service.BpmProcessService;
@@ -17,6 +11,7 @@ import org.hswebframework.web.workflow.flowable.utils.FlowableAbstract;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
 
 import javax.annotation.Resource;
 import java.io.InputStream;
@@ -28,21 +23,25 @@ import java.util.Map;
  * @Date 2017/8/7.
  */
 @Service
+@Transactional(rollbackFor = Throwable.class)
 public class BpmProcessServiceImp extends FlowableAbstract implements BpmProcessService {
     protected Logger logger = LoggerFactory.getLogger(this.getClass());
 
     @Resource
-    BpmTaskService bpmTaskService;
+   private BpmTaskService bpmTaskService;
 
     @Override
-    public ProcessInstance startProcessInstance(String creator_id,String procDefKey,String activity,String next_claim,
-                                String businessKey,
-                                Map<String, Object> variables){
+    public ProcessInstance startProcessInstance(String creatorId,
+                                                String procDefKey,
+                                                String activity,
+                                                String nextClaim,
+                                                String businessKey,
+                                                Map<String, Object> variables){
         logger.debug("start flow :", procDefKey);
         ProcessInstance processInstance = null;
         try{
             // 用来设置启动流程的人员ID,引擎会自动把用户ID保存到activiti:initiator中
-            identityService.setAuthenticatedUserId(creator_id);
+            identityService.setAuthenticatedUserId(creatorId);
             logger.debug("流程启动,work_flow_key:{}", procDefKey);
             logger.debug("表单ID,businessKey:{}",businessKey);
             logger.debug("流程变量保存,variables:{}",variables);
@@ -54,17 +53,17 @@ public class BpmProcessServiceImp extends FlowableAbstract implements BpmProcess
             List<Task> tasks = bpmTaskService.selectTaskByProcessId(processInstanceId);
             //如果指定了下一步执行环节,则将流程跳转到指定环节,并删除当前未执行的环节历史信息
             if(!StringUtils.isNullOrEmpty(activity)){
-                bpmTaskService.jumpTask(processInstanceId,activity,StringUtils.isNullOrEmpty(next_claim)?"":next_claim);
+                bpmTaskService.jumpTask(processInstanceId,activity,StringUtils.isNullOrEmpty(nextClaim)?"":nextClaim);
                 bpmTaskService.removeHiTask(tasks.get(0).getId());
             }
 //            else{
 //                //流程签收,签收人为指定办理人
-//                if(!StringUtils.isNullOrEmpty(next_claim))
-//                    bpmTaskService.claim(task.getId(), next_claim);
+//                if(!StringUtils.isNullOrEmpty(nextClaim))
+//                    bpmTaskService.claim(task.getId(), nextClaim);
 //            }
 
             if (logger.isDebugEnabled())
-                logger.debug("start process of {key={}, bkey={}, pid={}, variables={}}", new Object[]{procDefKey, businessKey, processInstanceId, variables});
+                logger.debug("start process of {key={}, bkey={}, pid={}, variables={}}", procDefKey, businessKey, processInstanceId, variables);
         }catch (Exception e){
             logger.warn("工作流启动失败,请联系管理员!");
         }finally {
@@ -102,8 +101,7 @@ public class BpmProcessServiceImp extends FlowableAbstract implements BpmProcess
     public InputStream findProcessPic(String procDefId) {
         ProcessDefinition definition = getProcessDefinitionById(procDefId);
         String source = definition.getDiagramResourceName();
-        InputStream inputStream = repositoryService.getResourceAsStream(definition.getDeploymentId(),source);
-        return inputStream;
+        return repositoryService.getResourceAsStream(definition.getDeploymentId(),source);
     }
 
     @Override

+ 54 - 53
hsweb-system/hsweb-system-workflow/hsweb-system-workflow-flowable/src/main/java/org/hswebframework/web/workflow/flowable/service/imp/BpmTaskServiceImp.java

@@ -1,35 +1,29 @@
 package org.hswebframework.web.workflow.flowable.service.imp;
 
-import org.activiti.engine.TaskService;
 import org.activiti.engine.history.HistoricProcessInstance;
 import org.activiti.engine.history.HistoricTaskInstance;
 import org.activiti.engine.impl.RepositoryServiceImpl;
 import org.activiti.engine.impl.TaskServiceImpl;
-import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
-import org.activiti.engine.impl.persistence.entity.JobEntity;
 import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
 import org.activiti.engine.impl.pvm.PvmActivity;
 import org.activiti.engine.impl.pvm.PvmTransition;
+import org.activiti.engine.impl.pvm.delegate.ActivityExecution;
 import org.activiti.engine.impl.pvm.process.ActivityImpl;
-import org.activiti.engine.impl.pvm.process.ProcessDefinitionImpl;
 import org.activiti.engine.impl.pvm.process.TransitionImpl;
-import org.activiti.engine.impl.pvm.runtime.ExecutionImpl;
-import org.activiti.engine.impl.task.TaskDefinition;
-import org.activiti.engine.repository.ProcessDefinition;
 import org.activiti.engine.runtime.Execution;
 import org.activiti.engine.runtime.ProcessInstance;
 import org.activiti.engine.task.Task;
-import org.hswebframework.utils.ClassUtils;
 import org.hswebframework.utils.StringUtils;
 import org.hswebframework.web.NotFoundException;
 import org.hswebframework.web.workflow.flowable.entity.TaskInfo;
-import org.hswebframework.web.workflow.flowable.service.BpmTaskService;
 import org.hswebframework.web.workflow.flowable.service.BpmActivityService;
+import org.hswebframework.web.workflow.flowable.service.BpmTaskService;
 import org.hswebframework.web.workflow.flowable.utils.FlowableAbstract;
 import org.hswebframework.web.workflow.flowable.utils.JumpTaskCmd;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
 
 import javax.annotation.Resource;
 import java.util.*;
@@ -39,12 +33,13 @@ import java.util.*;
  * @Date 2017/8/7.
  */
 @Service
+@Transactional(rollbackFor = Throwable.class)
 public class BpmTaskServiceImp extends FlowableAbstract implements BpmTaskService {
 
     protected Logger logger = LoggerFactory.getLogger(this.getClass());
 
     @Resource
-    BpmActivityService bpmActivityService;
+    private BpmActivityService bpmActivityService;
 
     @Override
     public List<Task> selectNowTask(String procInstId) {
@@ -112,7 +107,11 @@ public class BpmTaskServiceImp extends FlowableAbstract implements BpmTaskServic
     public List<TaskInfo> claimList(String userId) {
         List<TaskInfo> list = new ArrayList<>();
         // 等待签收的任务
-        List<Task> todoList = taskService.createTaskQuery().taskCandidateUser(userId).includeProcessVariables().active().list();
+        List<Task> todoList = taskService.createTaskQuery()
+                .taskCandidateUser(userId)
+                .includeProcessVariables()
+                .active()
+                .list();
         return list;
     }
 
@@ -120,19 +119,23 @@ public class BpmTaskServiceImp extends FlowableAbstract implements BpmTaskServic
     public List<TaskInfo> todoList(String userId) {
         List<TaskInfo> list = new ArrayList<>();
         // 已经签收的任务
-        List<Task> todoList = taskService.createTaskQuery().taskAssignee(userId).includeProcessVariables().active().list();
+        List<Task> todoList = taskService.createTaskQuery()
+                .taskAssignee(userId)
+                .includeProcessVariables()
+                .active()
+                .list();
         return list;
     }
 
     @Override
-    public void complete(String taskId, String userId, String activityId, String next_claim) {
+    public void complete(String taskId, String userId, String activityId, String nextClaim) {
         Task task = taskService.createTaskQuery().taskId(taskId).includeProcessVariables().singleResult();
         if (task == null) {
             logger.warn("任务不存在!");
             throw new NotFoundException("task not found");
         }
         String assignee = task.getAssignee();
-        if (null == assignee){
+        if (null == assignee) {
             logger.warn("请先签收任务!");
             throw new NotFoundException("Please sign for the task first");
         }
@@ -140,13 +143,13 @@ public class BpmTaskServiceImp extends FlowableAbstract implements BpmTaskServic
             logger.warn("只能完成自己的任务");
             throw new NotFoundException("You can only do your own work");
         }
-        Map<String,Object> map = new HashMap<>();
-        map.put("oldTaskId",task.getId());
+        Map<String, Object> map = new HashMap<>();
+        map.put("oldTaskId", task.getId());
         //完成此任务
         if (activityId == null) {
             taskService.complete(taskId, map);
         } else {
-            jumpTask(taskId, activityId, next_claim);
+            jumpTask(taskId, activityId, nextClaim);
         }
 
         //根据流程ID查找执行计划,存在则进行下一步,没有则结束(定制化流程预留)
@@ -154,63 +157,62 @@ public class BpmTaskServiceImp extends FlowableAbstract implements BpmTaskServic
         if (execution.size() > 0) {
             String tasknow = selectNowTaskId(task.getProcessInstanceId());
             // 自定义下一执行人
-            if (!StringUtils.isNullOrEmpty(next_claim))
-                claim(tasknow, next_claim);
+            if (!StringUtils.isNullOrEmpty(nextClaim))
+                claim(tasknow, nextClaim);
         }
     }
 
     @Override
     public void reject(String taskId) {
         // 先判定是否存在历史环节
-        String oldTaskId = selectVariableLocalByTaskId(taskId,"oldTaskId").toString();
+        String oldTaskId = selectVariableLocalByTaskId(taskId, "oldTaskId").toString();
         HistoricTaskInstance taskInstance = historyService.createHistoricTaskInstanceQuery().taskId(oldTaskId).singleResult();
-        if(taskInstance==null){
-            logger.error("历史任务环节不存在,taskId:"+oldTaskId);
+        if (taskInstance == null) {
+            throw new NotFoundException("历史任务环节不存在,taskId:" + oldTaskId);
         }
 
         Task task = selectTaskByTaskId(taskId);
 
         ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
         if (processInstance == null) {
-            logger.error("流程已经结束");
+            throw new NotFoundException("流程已经结束");
         }
 
         Map<String, Object> variables = processInstance.getProcessVariables();
 
-                ProcessDefinitionEntity definition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService).getDeployedProcessDefinition(task.getProcessDefinitionId());
+        ProcessDefinitionEntity definition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService).getDeployedProcessDefinition(task.getProcessDefinitionId());
         if (definition == null) {
-            logger.error("流程定义未找到");
+            throw new NotFoundException("流程定义未找到");
         }
 
-        ExecutionEntity execution = (ExecutionEntity) runtimeService.createExecutionQuery().executionId(task.getExecutionId()).singleResult();
+        ActivityExecution execution = (ActivityExecution) runtimeService.createExecutionQuery()
+                .executionId(task.getExecutionId()).singleResult();
         // 是否并行节点
-        if(execution.isConcurrent()){
-            logger.error("并行节点不允许驳回,taskId:"+task.getId());
+        if (execution.isConcurrent()) {
+            throw new NotFoundException("并行节点不允许驳回,taskId:" + task.getId());
         }
 
         // 是否存在定时任务
         long num = managementService.createJobQuery().executionId(task.getExecutionId()).count();
-        if(num>0) throw new NotFoundException("当前环节不允许驳回");
+        if (num > 0) throw new NotFoundException("当前环节不允许驳回");
 
         // 驳回
 
 
         // 取得上一步活动
-        ActivityImpl currActivity = ((ProcessDefinitionImpl) definition).findActivity(task.getTaskDefinitionKey());
+        ActivityImpl currActivity = definition.findActivity(task.getTaskDefinitionKey());
         List<PvmTransition> nextTransitionList = currActivity.getIncomingTransitions();
         // 清除当前活动的出口
-        List<PvmTransition> oriPvmTransitionList = new ArrayList<PvmTransition>();
+        List<PvmTransition> oriPvmTransitionList = new ArrayList<>();
         List<PvmTransition> pvmTransitionList = currActivity.getOutgoingTransitions();
-        for (PvmTransition pvmTransition : pvmTransitionList) {
-            oriPvmTransitionList.add(pvmTransition);
-        }
+        oriPvmTransitionList.addAll(pvmTransitionList);
         pvmTransitionList.clear();
 
         // 建立新出口
-        List<TransitionImpl> newTransitions = new ArrayList<TransitionImpl>();
+        List<TransitionImpl> newTransitions = new ArrayList<>();
         for (PvmTransition nextTransition : nextTransitionList) {
             PvmActivity nextActivity = nextTransition.getSource();
-            ActivityImpl nextActivityImpl = ((ProcessDefinitionImpl) definition).findActivity(nextActivity.getId());
+            ActivityImpl nextActivityImpl = definition.findActivity(nextActivity.getId());
             TransitionImpl newTransition = currActivity.createOutgoingTransition();
             newTransition.setDestination(nextActivityImpl);
             newTransitions.add(newTransition);
@@ -227,9 +229,7 @@ public class BpmTaskServiceImp extends FlowableAbstract implements BpmTaskServic
         for (TransitionImpl transitionImpl : newTransitions) {
             currActivity.getOutgoingTransitions().remove(transitionImpl);
         }
-        for (PvmTransition pvmTransition : oriPvmTransitionList) {
-            pvmTransitionList.add(pvmTransition);
-        }
+        pvmTransitionList.addAll(oriPvmTransitionList);
 
     }
 
@@ -252,7 +252,7 @@ public class BpmTaskServiceImp extends FlowableAbstract implements BpmTaskServic
     public void endProcess(String procInstId) {
         ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(procInstId).singleResult();
         ActivityImpl activity = bpmActivityService.getEndEvent(processInstance.getProcessDefinitionId());
-        jumpTask(procInstId,activity.getId(),null);
+        jumpTask(procInstId, activity.getId(), null);
     }
 
     @Override
@@ -277,15 +277,16 @@ public class BpmTaskServiceImp extends FlowableAbstract implements BpmTaskServic
 
     @Override
     public ActivityImpl selectActivityImplByTask(String taskId) {
-        if(StringUtils.isNullOrEmpty(taskId)){
-            return new ActivityImpl(null,null);
+        if (StringUtils.isNullOrEmpty(taskId)) {
+            return new ActivityImpl(null, null);
         }
         Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
         ProcessDefinitionEntity entity = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService).getDeployedProcessDefinition(task.getProcessDefinitionId());
         List<ActivityImpl> activities = entity.getActivities();
         ActivityImpl activity = null;
-        for(ActivityImpl activity1 : activities){
-            if(activity1.getProperty("type").equals("userTask") && activity1.getProperty("name").equals(task.getName())){
+        for (ActivityImpl activity1 : activities) {
+            if ("userTask".equals(activity1.getProperty("type")) &&
+                    activity1.getProperty("name").equals(task.getName())) {
                 activity = activity1;
             }
         }
@@ -293,12 +294,12 @@ public class BpmTaskServiceImp extends FlowableAbstract implements BpmTaskServic
     }
 
     @Override
-    public Map<String,Object> getUserTasksByProcDefKey(String procDefKey){
+    public Map<String, Object> getUserTasksByProcDefKey(String procDefKey) {
         String definitionId = repositoryService.createProcessDefinitionQuery().processDefinitionKey(procDefKey).orderByProcessDefinitionVersion().desc().list().get(0).getId();
-        List<ActivityImpl> activitiList = bpmActivityService.getUserTasksByProcDefId(definitionId);
-        Map<String,Object> map = new HashMap<>();
-        for(ActivityImpl activity:activitiList){
-            map.put(activity.getId(),activity.getProperty("name"));
+        List<ActivityImpl> activities = bpmActivityService.getUserTasksByProcDefId(definitionId);
+        Map<String, Object> map = new HashMap<>();
+        for (ActivityImpl activity : activities) {
+            map.put(activity.getId(), activity.getProperty("name"));
         }
         return map;
     }
@@ -306,10 +307,10 @@ public class BpmTaskServiceImp extends FlowableAbstract implements BpmTaskServic
     @Override
     public Map<String, Object> getUserTasksByProcInstId(String procInstId) {
         String definitionId = runtimeService.createProcessInstanceQuery().processInstanceId(procInstId).singleResult().getProcessDefinitionId();
-        List<ActivityImpl> activitiList = bpmActivityService.getUserTasksByProcDefId(definitionId);
-        Map<String,Object> map = new HashMap<>();
-        for(ActivityImpl activity:activitiList){
-            map.put(activity.getId(),activity.getProperty("name"));
+        List<ActivityImpl> activities = bpmActivityService.getUserTasksByProcDefId(definitionId);
+        Map<String, Object> map = new HashMap<>();
+        for (ActivityImpl activity : activities) {
+            map.put(activity.getId(), activity.getProperty("name"));
         }
         return map;
     }

+ 2 - 4
hsweb-system/hsweb-system-workflow/hsweb-system-workflow-flowable/src/main/java/org/hswebframework/web/workflow/flowable/utils/FlowableAbstract.java

@@ -1,12 +1,12 @@
 package org.hswebframework.web.workflow.flowable.utils;
 
-import com.fasterxml.jackson.databind.ObjectMapper;
 import org.activiti.engine.*;
 
 import javax.annotation.Resource;
 
 /**
- * Created by Administrator on 2017/7/26.
+ * @author wangwei
+ * @author zhouhao
  */
 public abstract class FlowableAbstract {
     @Resource
@@ -25,6 +25,4 @@ public abstract class FlowableAbstract {
     protected ManagementService managementService;
     @Resource
     protected FormService bpmFormService;
-    @Resource
-    protected ObjectMapper objectMapper;
 }