- 引入依赖
【注意:由于会自动引入mybatis依赖,所以如果引入后启动项目报错,可把mybatis依赖排除。】
<dependency>
<groupId>org.activiti</groupId>
<artifactId>activiti-spring-boot-starter</artifactId>
<version>7.0.0.Beta2</version>
</dependency>
<dependency>
<groupId>org.activiti</groupId>
<artifactId>activiti-image-generator</artifactId>
<version>7.1.0.M6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
- application.yml配置
【注意:activiti7配置信息,不要放在boostrap.yml 里面,我这边自测启动会报错。】
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/activiti2?useUnicode=true&characterEncoding=utf-8&useSSL=false&nullCatalogMeansCurrent=true
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
application:
name: actdemo
activiti:
database-schema: ACTIVITI
database-schema-update: true
history-level: full
db-history-used: true
jpa:
show-sql: true
package com.example.util;
import com.sun.istack.internal.NotNull;
import org.activiti.bpmn.model.*;
import org.activiti.bpmn.model.Process;
import org.activiti.engine.*;
import org.activiti.engine.history.*;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.HistoricProcessInstanceEntityImpl;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.el.PropertyNotFoundException;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipInputStream;
@Component
public class Activiti7Util {
@Autowired
private RepositoryService repositoryService;
@Autowired
private RuntimeService runtimeService;
@Autowired
private TaskService taskService;
@Autowired
private HistoryService historyService;
@Autowired
private ManagementService managementService;
public Map<String, Object> importProcess(MultipartFile file ,MultipartFile imgFile, String name ,
String bpmnResourceName , String imgResourceName) throws Exception{
Resource resource = file.getResource();
DeploymentBuilder name1 = repositoryService
.createDeployment()
.name(name);
name1.addInputStream(bpmnResourceName, file.getInputStream());
if (imgResourceName != null){
name1.addInputStream(imgResourceName, imgFile.getInputStream());
}
Deployment deployment = name1.deploy();
return getMap(deployment);
}
public Map<String, Object> importProcessByResources(@NotNull String name , @NotNull String bpmnName , String bpmnImgName){
DeploymentBuilder deployment = repositoryService.createDeployment();
deployment.name(name);
deployment.addClasspathResource("processes/"+bpmnName);
if (bpmnImgName != null){
deployment.addClasspathResource("processes/"+bpmnImgName);
}
Deployment deploy = deployment.deploy();
return getMap(deploy);
}
public Map<String, Object> importProcessByZip(String zipPath , String name ) throws FileNotFoundException {
FileInputStream fileInputStream = new FileInputStream(zipPath);
ZipInputStream stream = new ZipInputStream(fileInputStream);
Deployment deploy = repositoryService.createDeployment()
.addZipInputStream(stream)
.name(name)
.deploy();
return getMap(deploy);
}
private Map<String, Object> getMap(Deployment deploy) {
Map<String, Object> map = new HashMap<>(3);
System.out.println("部署ID:" + deploy.getId());
System.out.println("部署Name:" + deploy.getName());
System.out.println("部署时间:" + deploy.getDeploymentTime());
map.put("deploymentId", deploy.getId());
map.put("deploymentName", deploy.getName());
map.put("deploymentTime", deploy.getDeploymentTime());
return map;
}
public List<Map<String, Object>> queryProcessDefinition(String key){
ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery();
if (key != null){
query.processDefinitionKey(key);
}
List<Map<String, Object>> result = new ArrayList<>();
List<ProcessDefinition> list = query.list();
for (ProcessDefinition processDefinition : list) {
System.out.println("流程定义id="+processDefinition.getId());
System.out.println("流程定义名称="+processDefinition.getName());
System.out.println("流程定义key="+processDefinition.getKey());
System.out.println("流程定义版本="+processDefinition.getVersion());
System.out.println("流程部署id="+processDefinition.getDeploymentId());
Map<String, Object> map = new HashMap<>(5);
map.put("deploymentId", processDefinition.getDeploymentId());
map.put("processDefinitionId", processDefinition.getId());
map.put("processDefinitionKey", processDefinition.getKey());
map.put("processDefinitionName", processDefinition.getName());
map.put("processDefinitionVersion", processDefinition.getVersion());
result.add(map);
}
return result;
}
public void deleteProcessDefinition(String deploymentId , boolean cascade) {
repositoryService.deleteDeployment(deploymentId, cascade);
System.out.println("删除流程部署信息成功");
}
public void downDeployment(String key ,String imgSavePath,String bpmnSavePath) {
ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery();
query.processDefinitionKey(key);
for (ProcessDefinition processDefinition : query.list()) {
String deploymentId = processDefinition.getDeploymentId();
String pngName = processDefinition.getDiagramResourceName();
InputStream resourceAsStream = repositoryService.getResourceAsStream(deploymentId, pngName);
String bpmnName = processDefinition.getResourceName();
InputStream bpmnNameResourceAsStream = repositoryService.getResourceAsStream(deploymentId, bpmnName);
File pngFile = new File(imgSavePath);
File bpmnFile = new File(bpmnSavePath);
FileOutputStream pngFileOutputStream = null;
FileOutputStream bpmnFileOutputStream = null;
try{
pngFileOutputStream = new FileOutputStream(pngFile);
bpmnFileOutputStream = new FileOutputStream(bpmnFile);
IOUtils.copy(resourceAsStream, pngFileOutputStream);
IOUtils.copy(bpmnNameResourceAsStream, bpmnFileOutputStream);
}catch(Exception e){
e.printStackTrace();
}finally {
try {
resourceAsStream.close();
bpmnNameResourceAsStream.close();
assert pngFileOutputStream != null;
assert bpmnFileOutputStream != null;
pngFileOutputStream.close();
bpmnFileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("操作成功");
}
public void startProcessInstanceByKey(String processDefinitionId, String businessKey , Map<String,Object> params ){
ProcessInstance one = runtimeService.startProcessInstanceByKey(processDefinitionId, params);
System.out.println("流程定义id:"+one.getProcessDefinitionId());
System.out.println("流程实例id:"+one.getId());
System.out.println("当前活动id:"+one.getActivityId());
System.out.println("当前业务id:"+one.getBusinessKey());
System.out.println(one.getProcessVariables());
System.out.println("===============启动成功==================");
}
public List<Map<String, Object>> taskListByCandidateUser( String key ,String candidateUserName){
List<Task> taskList = taskService.createTaskQuery().processDefinitionKey(key).list();
List<Map<String, Object>> result = new ArrayList<>();
for (Task task : taskList) {
System.out.println("任务ID:" + task.getId());
System.out.println("任务名称:" + task.getName());
System.out.println("任务创建时间:" + task.getCreateTime());
System.out.println("任务委派人:" + task.getAssignee());
System.out.println("流程实例ID:" + task.getProcessInstanceId());
List<IdentityLink> linksForTask = taskService.getIdentityLinksForTask(task.getId());
for (IdentityLink link : linksForTask) {
System.out.println("候选人:"+link.getUserId());
System.out.println("组id:"+link.getGroupId());
System.out.println("候选类型:"+link.getType());
if (candidateUserName.equals(link.getUserId())){
List<String> collect = linksForTask.stream().map(IdentityLink::getUserId).collect(Collectors.toList());
Map<String, Object> map = new HashMap<>(8);
map.put("taskId", task.getId());
map.put("taskName", task.getName());
map.put("createTime", task.getCreateTime());
map.put("taskAssignee", task.getAssignee());
map.put("processInstanceId", task.getProcessInstanceId());
map.put("candidateList", collect);
map.put("candidateType", link.getType());
result.add(map);
break;
}
}
}
return result;
}
public boolean claimTask( String taskId , String candidateUserName ){
Task task = taskService.createTaskQuery()
.taskId(taskId)
.singleResult();
if (task != null && isCandidate(taskId, candidateUserName)){
taskService.claim(task.getId(), candidateUserName);
System.out.println("拾取任务成功,往下可以继续完成改任务");
return true;
}
System.out.println("【error】拾取任务失败,没有查到对应任务");
return false;
}
private boolean isCandidate(String taskId , String candidateUserName ){
for (IdentityLink link : taskService.getIdentityLinksForTask(taskId)) {
if (candidateUserName.equals(link.getUserId())){
return true;
}
}
return false;
}
public boolean claimTaskReturn( String taskId , String candidateUserName ){
Task task = taskService.createTaskQuery()
.taskId(taskId)
.taskCandidateUser(candidateUserName)
.singleResult();
if (task != null){
taskService.setAssignee(task.getId(), null);
System.out.println("归还任务成功");
return true;
}
System.out.println("【error】归还任务失败,没有查到任务");
return false;
}
public boolean taskHandover(String taskId , String candidateUserName, String assigneeName ){
Task task = taskService.createTaskQuery()
.taskId(taskId)
.taskCandidateUser(candidateUserName)
.singleResult();
if (task != null){
taskService.setAssignee(task.getId(), assigneeName);
System.out.println("交接成功");
return true;
}
System.out.println("【error】交接失败,没有查到任务");
return false;
}
public List<Map<String, Object> > taskListByMy(String taskAssignName , String key , Integer firstResult , Integer maxResults){
List<Task> list = taskService.createTaskQuery()
.processDefinitionKey(key)
.taskAssignee(taskAssignName)
.listPage(firstResult, maxResults);
List<Map<String, Object> > result = new ArrayList<>();
for (Task task : list) {
System.out.println("流程定义id="+task.getProcessDefinitionId());
System.out.println("任务id="+task.getId());
System.out.println("任务负责人="+task.getAssignee());
System.out.println("任务名称="+task.getName());
Map<String, Object> taskMap = new HashMap<>(5);
taskMap.put("taskId", task.getId());
taskMap.put("taskName", task.getName());
taskMap.put("createTime", task.getCreateTime());
taskMap.put("taskAssignee", task.getAssignee());
taskMap.put("processInstanceId", task.getProcessInstanceId());
result.add(taskMap);
}
return result;
}
public boolean completeTask( String taskAssignName , String taskId , Map<String, Object> params){
try{
Task task = taskService.createTaskQuery()
.taskId(taskId)
.taskAssignee(taskAssignName)
.singleResult();
if (task == null){
System.out.println("【error】 说明根据任务id和人名 无法查到待办的指定任务");
return false;
}
taskService.complete(taskId ,params);
System.out.println("任务完成成功");
return true;
}catch(ActivitiException ee){
ee.printStackTrace();
System.out.println( "【error】流程线上已经绑定变量了:"+ee.getMessage());
return false;
}catch(Exception e){
e.printStackTrace();
System.out.println("【error】 执行报错: "+e.getMessage());
return false;
}
}
public boolean claimTaskAndCompleteTask(String taskId, String candidateUserName , Map<String, Object> params){
if (this.claimTask(taskId,candidateUserName)){
this.completeTask(candidateUserName, taskId,params);
return true;
};
System.out.println( "【error】没有可以拾取的任务");
return false;
}
public List<HistoricActivityInstance> historicActivityInstanceList(String processDefinitionId , String processInstanceId,String assigneeName ){
HistoricActivityInstanceQuery instanceQuery = historyService.createHistoricActivityInstanceQuery();
if (processDefinitionId != null){
instanceQuery.processDefinitionId(processDefinitionId);
}
if (processInstanceId != null){
instanceQuery.processInstanceId(processInstanceId);
}
if (assigneeName != null){
instanceQuery.taskAssignee(assigneeName);
}
List<HistoricActivityInstance> list = instanceQuery.list();
long count = instanceQuery.count();
for (HistoricActivityInstance instance : list) {
System.out.println(instance.toString());
}
return list;
}
public void suspendAllProcessInstance( String key ){
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey(key).singleResult();
boolean suspended = processDefinition.isSuspended();
String processDefinitionId = processDefinition.getId();
if (suspended){
repositoryService.activateProcessDefinitionById(processDefinitionId, true, null);
System.out.println("对流程定义id为"+processDefinitionId+",进行[激活]操作");
}else{
repositoryService.activateProcessDefinitionById(processDefinitionId, false, null);
System.out.println("对流程定义id为"+processDefinitionId+",进行[挂起]操作");
}
System.out.println("流程定义"+processDefinition.getName()+"已经操作成功【包括关联的所有实例】");
}
public void suspendProcessInstanceByProcessInstanceId( String processInstanceId ){
ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
if (instance.isSuspended()){
runtimeService.activateProcessInstanceById(instance.getId());
System.out.println("流程实例id="+instance.getId()+",已激活");
}else{
runtimeService.suspendProcessInstanceById(instance.getId());
System.out.println("流程实例id="+instance.getId()+",已挂起");
}
System.out.println("单个流程实例:"+instance.getName()+",已经操作成功");
}
public void xx(@NotNull String processInstanceId, HttpServletResponse response)
throws IOException {
ExecutionEntity pi = (ExecutionEntity) runtimeService
.createProcessInstanceQuery()
.processInstanceId(processInstanceId).singleResult();
if (pi == null) {
xx2(processInstanceId, response);
return;
}
ProcessDefinitionEntity pde = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
.getDeployedProcessDefinition(pi.getProcessDefinitionId());
List<String> highLightedActivities = getHighLightedActivities(processInstanceId);
List<String> highLightedFlows = runtimeService.getActiveActivityIds(processInstanceId);
if (pde != null && pde.isGraphicalNotationDefined()) {
BpmnModel bpmnModel = repositoryService.getBpmnModel(pde.getId());
ProcessDiagramGenerator ge = new DefaultProcessDiagramGenerator();
InputStream resource = getResource(highLightedActivities, highLightedFlows, bpmnModel, ge);
int len = 0;
byte[] b = new byte[1024];
while ((len = resource.read(b, 0, 1024)) != -1) {
response.getOutputStream().write(b, 0, len);
}
} else {
throw new ActivitiException("Process instance with id "
+ processInstanceId + " has no graphic description");
}
}
private void xx2(String processInstanceId, HttpServletResponse response)throws IOException {
HistoricProcessInstanceEntityImpl pi = (HistoricProcessInstanceEntityImpl)historyService.createHistoricProcessInstanceQuery()
.processInstanceId(processInstanceId).singleResult();
if (pi == null){
throw new ActivitiObjectNotFoundException(
"Process instance with id" + processInstanceId
+ " could not be found", ProcessInstance.class);
}
ProcessDefinitionEntity pde = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
.getDeployedProcessDefinition(pi.getProcessDefinitionId());
List<String> highLightedActivities = getHighLightedActivities(processInstanceId);
if (pde != null && pde.isGraphicalNotationDefined()) {
BpmnModel bpmnModel = repositoryService.getBpmnModel(pde.getId());
ProcessDiagramGenerator ge = new DefaultProcessDiagramGenerator();
List<String> highLightedFlows = historyService.getHistoricIdentityLinksForProcessInstance(processInstanceId).stream()
.map(HistoricIdentityLink::getTaskId).collect(Collectors.toList());
InputStream resource = getResource(highLightedActivities, highLightedFlows, bpmnModel, ge);
int len = 0;
byte[] b = new byte[1024];
while ((len = resource.read(b, 0, 1024)) != -1) {
response.getOutputStream().write(b, 0, len);
}
} else {
throw new ActivitiException("Process instance with id "
+ processInstanceId + " has no graphic description");
}
}
private List<String> getHighLightedActivities(@NotNull String processInstanceId) {
List<HistoricActivityInstance> highLightedActivitList = historyService.createHistoricActivityInstanceQuery()
.processInstanceId(processInstanceId).list();
return highLightedActivitList.stream().map(HistoricActivityInstance::getActivityId).collect(Collectors.toList());
}
private InputStream getResource(List<String> highLightedActivities, List<String> highLightedFlows, BpmnModel bpmnModel, ProcessDiagramGenerator ge) {
return ge.generateDiagram(bpmnModel, highLightedActivities,
highLightedFlows,
"宋体", "宋体", null, false);
}
}
@Controller
@RequestMapping("/act")
public class ActivityController {
@Resource
private Activiti7Util util;
public static String bpmnProcessId = "Process_test";
public static Map<String, String> map = new HashMap<>();
public static String assigneeName = "小明";
List<String> banzhangList = Arrays.asList("小黑班长","小白班长");
List<String> teacherList = Arrays.asList("老师A","老师B");
List<String> fuList = Arrays.asList("小粉副校长","小红副校长");
List<String> zhengList = Arrays.asList("小绿正校长","小蓝正校长");
@RequestMapping("/bushu")
@ResponseBody
public Object bushu( @RequestParam Map<String, Object> params ){
String name = "请假条";
String bpmnName = "qingjia.bpmn";
String bpmnImgName = "qingjia.svg";
Map<String, Object> deployment = util.importProcessByResources(name, bpmnName, bpmnImgName);
return deployment;
}
@RequestMapping("/kaishi")
@ResponseBody
public Object kaishi(String applyUserName){
Map<String, Object> params = new HashMap<>();
params.put("userName", applyUserName);
params.put("banzhangList", banzhangList);
params.put("teacherList", teacherList);
params.put("fuList", fuList);
params.put("zhengList", zhengList);
String businessKey = "这里是业务id";
util.startProcessInstanceByKey(bpmnProcessId, businessKey, params);
List<Map<String, Object>> tasks = util.taskListByMy(assigneeName, bpmnProcessId, 0, 100);
for (Map<String, Object> task : tasks) {
String taskId = (String) task.get("taskId");
util.completeTask(assigneeName , taskId,null);
}
return "success";
}
@RequestMapping("/shiquList")
@ResponseBody
public Object shiquList( @RequestParam Map<String, Object> params ){
String candidateUserName = "SYSTEM";
return util.taskListByCandidateUser(bpmnProcessId, candidateUserName);
}
@RequestMapping("/tongguo")
@ResponseBody
public Object tongguo( @RequestParam Map<String, Object> params ){
String taskId = "";
params.put("roomCheck", 1);
String candidateUserName = "SYSTEM";
return util.claimTaskAndCompleteTask(candidateUserName, taskId, params);
}
@RequestMapping("/lishi")
@ResponseBody
public Object historicActivityInstanceList( @RequestParam Map<String, Object> params ){
String definitionId = "resourcesOccupy3:2:bb047ad5-9ecd-11ec-a39b-080058000005";
String instanceId = null;
String assigneeName = "";
return util.historicActivityInstanceList(definitionId, instanceId , assigneeName);
}
}
demo地址
|