1. What is workflow
1.1 Workflow Introduction
Workflow is to automate the execution and management of business processes through computers. Its main solution is to "make the process of automatically transferring documents, information or tasks among multiple participants according to some predefined rules, so as to achieve a desired business goal, or to promote the realization of this goal".
1.2 Workflow System
A software system has the function of workflow. We call it workflow system. What is the function of workflow in a system? It is to manage the business process of the system automatically, so the workflow is based on the business process, so the core of a software system is the business process of the system fundamentally, and the workflow is only to assist in the business process management. Even if there is no workflow business system, it can be developed and run, but it can better manage business processes and improve the scalability of the system.
1.2.1 Applicable industries
Consumer goods industry, manufacturing industry, telecommunications service industry, banking and securities insurance and other financial services, logistics service industry, property service industry, property management, large and medium-sized import and export trading companies, government institutions, research institutes and education services, especially large multinational enterprises and group companies.
1.2.2 Specific Application
- Key business processes: order, quotation processing, contract audit, customer telephone processing, supply chain management, etc.
- Administrative management categories: travel applications, overtime applications, leave applications, car applications, applications for various office supplies, purchase applications, daily reports and other administrative forms handled by the original manual circulation.
- Personnel management: staff training arrangements, performance appraisal, job change processing, staff file information management, etc.
- Financial related categories: payment request, receivable processing, daily reimbursement processing, travel reimbursement, budget and plan application, etc.
- Customer service category: customer information management, customer complaints, request processing, after-sales service management, etc.
- Special service categories: ISO series corresponding process, quality management corresponding process, product data information management, customs declaration processing of trading companies, goods tracking processing of logistics companies and other tasks completed through the manual flow of forms can be implemented automatically and normatively by workflow software.
1.3 Workflow Implementation
Before there was no special workflow engine, in order to achieve process control, we usually used the value of the status field to track the change of the process. In this way, users with different roles decide whether the record is displayed or not by taking the value of the status field. For records that have permission to view, current users decide whether to approve qualified operations according to their roles. If qualified, set a value in the status field to represent qualified; of course, if not qualified, set a value to represent unqualified situations. This is the most primitive way. Although process control is achieved through the state field, when our process changes, the code written in this way also needs to be adjusted.
So is there a professional way to achieve workflow management? And after the change of business process, our program can not be changed. If this effect can be achieved, then the adaptability of our business system has been greatly improved.
2. What is Activiti
2.1 Introduction to Activiti
On May 17, 2010, Alfresco announced the formal launch of the Activiti Business Process Management (BPM) open source project. Its chief architect is Tom Baeyens, an expert in BPM. Tom Baeyens is the original jbpm architect, and jbpm is a well-known workflow engine, of course, activiti is also a well-known workflow engine. It is a workflow engine.
Activiti is a workflow engine. Actiti can extract complex business processes from business systems, define them using a special modeling language (BPMN2.0). Business systems are executed according to pre-defined processes. It realizes that business processes of business systems are managed by activiti, and reduces the number of business systems that are managed by BPMN2.0. In order to improve the robustness of the system and reduce the cost of system development and maintenance, the workload of system upgrade and transformation in process change is increased.
Official website: https://www.activiti.org/
2.1.1 BPM
BPM (Business Process Management), or Business Process Management (BPM), is a systematic method focusing on standardizing the construction of end-to-end excellent business processes and aiming at continuously improving the business performance of organizations. BPM is included in common business management education such as EMBA and MBA.
Enterprise process management is mainly to reform the internal enterprise, change the overlap of enterprise function management organizations, multi-level middle, non-closed-loop process, so that the organization does not overlap, business does not duplicate, to shorten the process cycle, save operating capital, improve the efficiency of enterprises.
2.1.2 BPM Software
BPM software is an IT tool that promotes the integration and adjustment of business methods and solutions among people, people and systems, and systems according to the changes of business environment in enterprises. Usually, information transmission, data synchronization, business monitoring and continuous upgrading and optimization of enterprise business processes are realized through the Internet, so as to achieve cross-application, cross-department, cross-partner and customer business operations. Through BPM software to model, automate, manage, monitor and optimize the whole life cycle of internal and external business processes, enterprise costs are reduced and profits are greatly increased.
BPM software is widely used in enterprises, where there are business processes, BPM software can be used to manage, such as enterprise personnel office management, procurement process management, document approval process management, financial management, etc.
2.1.3 BPMN
BPMN (Business Process Model And Notation) - Business process models and symbols are a set of standard business process modeling symbols developed by BPMI (Business Process Management Initiative). Business processes can be created using symbols provided by BPMN. BPMN 1.0 specification was released in May 2004. BPMI was incorporated into OMG (The Object Management Group Object Management Organization) in September 2005. OMG released the final version of BPMN 2.0 in January 2011.
The specific history of development is as follows:
BPMN is a widely accepted BPM standard by BPM manufacturers. Activiti is the use of BPMN 2.0 for process modeling and process execution management. It includes many modeling symbols, such as:
Event is represented by a circle, which is what happens in the process of running. Activities are represented by rounded rectangles, and a process consists of one or more activities.
2.2 How to use Activity
- Deploy activiti
Activiti is a workflow engine (in fact, a bunch of jar package API s). Business systems use activiti to manage their business processes automatically. In order to facilitate business systems to access (operate) activiti interfaces or functions, they usually integrate the activiti environment with the business system environment. - Process definition
Business processes (. bpmn files) are defined using the activity-designer tool. bpmn file is the business process definition file, which defines the business process through xml. If we use the working engine developed by other companies, we usually provide a visual modeling tool (Process Designer) to generate process definition files. The modeling tool is intuitive, and generally supports graphical drag-and-drop mode, multi-window user interface, rich process graphics elements, copy, paste and delete process elements. Except for other functions. - Process Definition Deployment
Deploy the business process definition (. bpmn file) to activiti. Deploy the. bpmn file to activiti using the api provided by activiti (in general, you need a picture of the business process deployed together. png) - Start a Process Instance
Starting a process instance means starting a business process, such as employee leave process deployment, if Zhang San wants leave, a process instance can be started, if Li Si wants leave, and a process instance can be started. The execution of the two processes does not affect each other. It is like defining a java class and instantiating two processes. Like objects, a deployed process is like a java class, and starting a process instance is like a new java object. - User Query to Do Task
Because now the system's business processes have been handed over to activiti management, through activiti can query where the current process is executed and what tasks the current user needs to deal with. These activiti help us manage, unlike above, we need to specify the status value of the current query in where condition of sql statement. - User Handles Tasks
After the user inquires about the to-do task, he can handle a certain task. If the task is completed, other users need to handle it. For example, after the purchase order is created, the Department Manager reviews it. This process is also completed by activiti for us. We do not need to hardcode the next task manager in the code. - Process End
This process instance is completed when there is no next task/node when the task is completed.
3. Environmental preparation
3.1 Development Environment
Jdk1.8 or more, Mysql 5 or more, Tomcat 8.5, IDEA or Eclipse tools. Note: Actiti's process definition tool plug-in can be installed under IDEA or Eclipse tools.
3.2 Activiti environment
Activiti7 supports spring 5 by default.
3.2.1 Download activiti7
Activiti Download Address: http://activiti.org/download.html
<dependencyManagement> <dependencies> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-dependencies</artifactId> <version>7.0.0.Beta1</version> <scope>import</scope> <type>pom</type> </dependency> </dependencies> </dependencyManagement>
- Database :
Actiti needs database support to run. The supported databases are h2, mysql, oracle, postgres, mssql, db2, etc. The directory stores activiti's table scripts. - Docs
Activiti Help Document. - Wars
The official sample project.
3.2.2 Activiti Designer Process Designer (Eclipse Tool)
This tutorial uses Activiti - Designer-eclipse-plugin (activiti process designer plug-in) to complete the process production. Install plug-ins online at http://activiti.org/designer/update/.
After successful installation, open the menu Windows - > Preferences - > Activiti - > Save to generate the flow chart:
3.2.2 Create Activiti Related Tables
Introducing Relevant Dependencies
<properties> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> </properties> <dependencies> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-engine</artifactId> <version>7.0.0.Beta1</version> </dependency> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-spring</artifactId> <version>7.0.0.Beta1</version> </dependency> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-bpmn-model</artifactId> <version>7.0.0.Beta1</version> </dependency> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-bpmn-converter</artifactId> <version>7.0.0.Beta1</version> </dependency> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-json-converter</artifactId> <version>7.0.0.Beta1</version> </dependency> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-bpmn-layout</artifactId> <version>7.0.0.Beta1</version> </dependency> <dependency> <groupId>org.activiti.cloud</groupId> <artifactId>activiti-cloud-services-api</artifactId> <version>7.0.0.Beta1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> </dependencies>
Modify configuration files
log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE. #log4j.rootCategory=INFO, CONSOLE debug info warn error fatal log4j.rootCategory=debug, CONSOLE, LOGFILE # Set the enterprise logger category to FATAL and its only appender to CONSOLE. log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE # CONSOLE is set to be a ConsoleAppender using a PatternLayout. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n # LOGFILE is set to be a File appender using a PatternLayout. log4j.appender.LOGFILE=org.apache.log4j.FileAppender log4j.appender.LOGFILE.File=d:\axis.log log4j.appender.LOGFILE.Append=true log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
activiti.cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/contex http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--Data source configuration dbcp--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/activiti" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <!--activiti Individually operated ProcessEngine Configuration object(processEngineConfiguration),Use separate boot mode //By default: the bean's id = process Engine Configuration --> <bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneProcessEngineConfiguration"> <!--Representational data sources--> <property name="dataSource" ref="dataSource"></property> <!-- <property name="jdbcDriver" value="com.mysql.jdbc.Driver" /> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/activiti" /> <property name="jdbcUsername" value="root" /> <property name="jdbcPassword" value="root" />--> <!--Represents whether a table structure is generated--> <property name="databaseSchemaUpdate" value="true"/> </bean> </beans>
The databaseSchemaUpdate attribute value:
false (default): Check the version of the database table and the version of the dependent library, and throw an exception if the version does not match.
true: When building a process engine, perform checks and update if necessary. If the table does not exist, it is created.
create-drop: Create database tables when building process engines and delete them when closing process engines.
drop-create: Delete the table before creating it.
create: create database tables when building process engines, and do not delete them when closing process engines.
Write code
//Create Process Engine Configuration ProcessEngineConfiguration configuration = ProcessEngineConfiguration .createProcessEngineConfigurationFromResource("activiti.cfg.xml") //Create Process Engine through Process Engine Configuration, at which point a database is created ProcessEngine processEngine = configuration.buildProcessEngine();
Run the above section to complete the activity database creation, 7 will create 25 tables.
Activiti tables all start with ACT_ The second part is the two-letter identification indicating the purpose of the table. Uses also correspond to service API s.
- ACT_RE_*:'RE'denotes repository. This prefix table contains process definitions and process static resources (pictures, rules, etc.).
- ACT_RU_*:'RU'denotes runtime. These runtime tables contain running data such as process instances, tasks, variables, asynchronous tasks, and so on. Activiti only saves these data during the execution of process instances and deletes these records at the end of the process. In this way, the runtime table can always be very small and fast.
- ACT_HI_*:'HI'denotes history. These tables contain historical data, such as historical process instances, variables, tasks, etc.
- AC T_GE_*: GE stands for general. General data for different scenarios.
4. Activiti Service Architecture Diagram
In the new version, we can find that both Serivce s of Identity Service and FormService have been deleted through experiments.
4.1 activiti.cfg.xml
Actitivity engine configuration file, including: Process Engine Configuration definition, data source definition, transaction manager, etc., is actually a spring configuration file.
4.2 ProcessEngineConfiguration
The configuration class of process engine can create workflow engine ProceccEngine through Process Engine Configuration. The two commonly used methods are as follows:
4.2.1 StandaloneProcessEngineConfiguration
Through org. activiti. engine. impl. cfg. Standalone Process Engine Configuration
Activiti can run independently and use the Process Engine it creates to handle transactions on its own.
Configuration file format:
Usually a bean with an id of process Engine Configuration is defined in the activiti.cfg.xml configuration file, where spring's dependency injection is used to build the engine.
<bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneProcessEngineConfig uration"> <!-- data source --> <property name="dataSource" ref="dataSource" /> <!-- Database Policy --> <property name="databaseSchemaUpdate" value="true"/> </bean>
4.2.2 SpringProcessEngineConfiguration
Integration with Spring through org. activiti. spring. Spring Process Engine Configuration.
Create an integrated configuration file for spring and activiti: activity-spring.cfg.xml (name is not fixed)
4.2.3 Create n Process Engine Configuration
ProcessEngineConfiguration configuration = ProcessEngineConfiguration .createProcessEngineConfigurationFromResource("activiti.cfg.xml")
The code above requires that there must be a bean of processEngineConfiguration in activiti.cfg.xml
You can also use the following method to change the name of the bean:
ProcessEngineConfiguration.createProcessEngineConfigurationFromResou rce(String resource, String beanName);
4.3 ProcessEngine
Workflow engine, which is equivalent to a facade interface, creates process Engine through Process Engine Configuration and service interfaces through Process Engine.
4.3.1 General Creation Method
//Create Process Engine through Process Engine Configuration ProcessEngine processEngine = processEngineConfiguration.buildProcessEngine();
4.3.2 Simple Creation Method
Fixed the activiti.cfg.xml file name and path, and the activiti.cfg.xml file has the configuration of process Engine Configuration. You can use the following code to create process Engine:
//Create process Engine using configuration in activiti.cfg.xml under classpath ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); System.out.println(processEngine);
4.4 Service
4.4.1 Service Creation
Service is created by Process Engine. Service is a service interface provided by workflow engine for workflow deployment, execution and management. The following are the ways:
RuntimeService runtimeService = processEngine.getRuntimeService(); RepositoryService repositoryService = processEngine.getRepositoryService(); TaskService taskService = processEngine.getTaskService();
4.4.2 Service Overview
- RepositoryService activiti resource management class
- RuntimeService activiti's Process Running Management Class
- TaskService activiti task management class
- HistoryService activiti history management class
- ManagerService activiti engine management class
4.4.3 RepositoryService
Actiti is a resource management class that provides operations to manage and control process publishing packages and process definitions. Business flow charts designed with workflow modeling tools need to use this service to deploy the content of the process definition file to the computer.
In addition to the deployment process definition, you can also: query the release package and process definition in the engine.
Suspend or activate publishing packages, corresponding to all and specific process definitions. Pause means that they can no longer perform any operations. Activation is the corresponding reverse operation. Get multiple resources, such as files contained in the release package, or flow charts automatically generated by the engine. Getting a pojo version of the process definition can be used to parse the process through java, rather than xml.
4.4.4 RuntimeService
It is the process operation management class of activiti. You can get a lot of information about process execution from this service class
4.4.5 TaskService
It is the task management class of activiti. Task information can be obtained from this class.
4.4.6 HistoryService
Actiti is a history management class, which can query history information. When executing a process, the engine will save a lot of data (according to configuration), such as process instance start time, task participants, task completion time, execution path of each process instance, and so on. This service mainly obtains these data through query function.
4.4.7 ManagementService
It is the engine management class of Activiti. It provides the management and maintenance functions of activity process engine. These functions are not used in workflow-driven applications, but are mainly used for daily maintenance of activity system.
5. Activiti Initial Experience
5.1 Process Definition
Install the activiti-designer plug-in in eclipse or idea to use. The drawing board includes the following nodes:
Connection-Connection, Event-Event, Task-Task, Gateway-Gateway, Container-Container,
Boundary event - boundary event, Intermediate event - intermediate event. The flow chart is designed and saved to generate. bpmn file.
5.1.1 Specify process definition key
Process definition key is the identification of process definition. In eclipse, the process key is viewed through the properties view.
Suggestion: The same business process defines the same key name. For example, if a new business process needs to be created, the leave process uses the new key.
5.1.2 Designation of Task-holders
In the properties view, specify the person responsible for each task node, such as zhangsan, who fills in the leave form below.
5.2 Process Definition Deployment
5.2.1 What is process definition deployment
Deploy the offline defined process to the activity database, which is the process definition deployment. By calling the api of activiti, the bpmn and png files of the process definition are added to activiti one by one, and the two files can also be deployed as zip packages.
5.2.2 Single file deployment
Deploy bpmn file and png picture file respectively.
@Test public void deployProcess() { // Get repository service RepositoryService repositoryService = processEngine.getRepositoryService(); // bpmn input stream InputStream inputStream_bpmn = this.getClass().getClassLoader().getResourceAsStream("diagram/holiday.bpmn"); // Picture input stream InputStream inputStream_png = this.getClass().getClassLoader().getResourceAsStream(" diagram/holiday.png"); // Process Deployment Objects Deployment deployment = repositoryService.createDeployment() .addInputStream("holiday.bpmn", inputStream_bpmn) .addInputStream("holiday.png", inputStream_png) .deploy(); System.out.println("Process deployment id: " + deployment.getId()); System.out.println("Process deployment name:" + deployment.getName()); }
After doing this, activiti saves the bpm files and picture files specified in the code above in the activiti database.
5.2.3 Compressed Packet Deployment
The holiday. BPMN and holiday. PNG are compressed into zip packets.
@Test public void deployProcessByZip() { //1. Create ProcessEngine objects ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); //2. Get an example of Repository Service RepositoryService repositoryService = processEngine.getRepositoryService(); //3. Convert to ZipInputStream stream object InputStream is = ActivitiDeployment.class.getClassLoader().getResourceAsStream("diagram/holidayBPMN.zip"); //Converting an inputstream stream stream to a ZipInputStream stream ZipInputStream zipInputStream = new ZipInputStream(is); //3. Deployment Deployment deployment = repositoryService.createDeployment() .addZipInputStream(zipInputStream) .name("Leave application process") .deploy(); //4. Output some deployment information System.out.println(deployment.getName()); System.out.println(deployment.getId()); }
5.3 Process Definition Query
@Test public void queryProceccDefinition() { // Process definition key String processDefinitionKey = "holiday"; // Get repository service RepositoryService repositoryService = processEngine .getRepositoryService(); // Query process definition ProcessDefinitionQuery processDefinitionQuery = repositoryService .createProcessDefinitionQuery(); //Traversing query results List<ProcessDefinition> list = processDefinitionQuery .processDefinitionKey(processDefinitionKey) .orderByProcessDefinitionVersion().desc().list(); for (ProcessDefinition processDefinition : list) { System.out.println("------------------------"); System.out.println(" Process deployment id : " + processDefinition.getDeploymentId()); System.out.println("Process definition id: " + processDefinition.getId()); System.out.println("Process Definition Name:" + processDefinition.getName()); System.out.println("Process definition key: " + processDefinition.getKey()); System.out.println("Process Definition Version:" + processDefinition.getVersion()); } }
5.4 Process Definition Delete
@Test public void deleteDeployment() { // process deployment id String deploymentId = "8801"; // Getting repository service through process engine RepositoryService repositoryService = processEngine .getRepositoryService(); // Delete the process definition, and if the process definition has an existing process instance started, the deletion error occurs repositoryService.deleteDeployment(deploymentId); // Set the true cascade deletion process definition, even if the process has a process instance start, it can be deleted. Set it to false for non-level deletion if the process //repositoryService.deleteDeployment(deploymentId, true); }
5.5 Process Definition Resource Query
5.5.1 Mode 1
Through process definition object, process definition resources are acquired, and bpmn and png are acquired.
@Test public void getProcessResources() throws IOException { // Process definition id String processDefinitionId = ""; // Get repository service RepositoryService repositoryService = processEngine .getRepositoryService(); // Process Definition Objects ProcessDefinition processDefinition = repositoryService .createProcessDefinitionQuery() .processDefinitionId(processDefinitionId).singleResult(); //Getting bpmn String resource_bpmn = processDefinition.getResourceName(); //Get png String resource_png = processDefinition.getDiagramResourceName(); // resource information System.out.println("bpmn: " + resource_bpmn); System.out.println("png: " + resource_png); File file_png = new File("d:/purchasingflow01.png"); File file_bpmn = new File("d:/purchasingflow01.bpmn"); // Output bpmn InputStream resourceAsStream = null; resourceAsStream = repositoryService.getResourceAsStream( processDefinition.getDeploymentId(), resource_bpmn); FileOutputStream fileOutputStream = new FileOutputStream(file_bpmn); byte[] b = new byte[1024]; int len = -1; while ((len = resourceAsStream.read(b, 0, 1024)) != -1) { fileOutputStream.write(b, 0, len); } // Output picture resourceAsStream = repositoryService.getResourceAsStream( processDefinition.getDeploymentId(), resource_png); fileOutputStream = new FileOutputStream(file_png); // byte[] b = new byte[1024]; // int len = -1; while ((len = resourceAsStream.read(b, 0, 1024)) != -1) { fileOutputStream.write(b, 0, len); } }
5.5.2 Mode 2
Access process definition resources by querying process deployment information.
// Getting Process Definition Picture Resources @Test public void getProcessResources() throws IOException { //Process deployment id String deploymentId = "9001"; // Getting repository service through process engine RepositoryService repositoryService = processEngine .getRepositoryService(); //Read the resource name List<String> resources = repositoryService.getDeploymentResourceNames(deploymentId); String resource_image = null; //Get pictures for(String resource_name :resources){ if(resource_name.indexOf(".png")>=0){ resource_image = resource_name; } } //Picture input stream InputStream inputStream = repositoryService.getResourceAsStream(deploymentId, resource_image); File exportFile = new File("d:/holiday.png"); FileOutputStream fileOutputStream = new FileOutputStream(exportFile); byte[] buffer = new byte[1024]; int len = -1; //Output picture while((len = inputStream.read(buffer))!=-1){ fileOutputStream.write(buffer, 0, len); } inputStream.close(); fileOutputStream.close(); }
5.6 Viewing Process History Information
Even if the process definition has been deleted, the historical information of process execution is stored in the act_hi_* related table of activiti through the previous analysis. So we can still query the history of process execution and view the relevant history through History Service.
public void testHistoric01(){ HistoryService historyService = pe.getHistoryService(); HistoricActivityInstanceQuery query = historyService.createHistoricActivityInstanceQuery(); query.processInstanceId("1501"); List<HistoricActivityInstance> list = query.list(); for(HistoricActivityInstance ai :list){ System.out.println(ai.getActivityId()); System.out.println(ai.getActivityName()); System.out.println(ai.getProcessDefinitionId()); System.out.println(ai.getProcessInstanceId()); System.out.println("=============================="); } }
5.7 Start a process instance
After process definition is deployed in activiti, the business process can be managed through workflow, that is to say, the leave application process deployed above can be used. For this process, starting a process means initiating a new leave application, which is equivalent to the relationship between the java class and the java object. Once the class is defined, it needs new to create an object to use. Of course, new objects can be used. For the leave application process, Zhang San needs to start a process instance to initiate a leave application form, and a process instance to initiate a leave application form.
// Start a process instance @Test public void startProcessInstance() { // Get RunTime Service RuntimeService runtimeService = processEngine.getRuntimeService(); // Define key startup process according to process ProcessInstance processInstance = runtimeService .startProcessInstanceByKey("myholiday01"); System.out.println(" Process definition id : " + processInstance.getProcessDefinitionId()); System.out.println("Process examples id: " + processInstance.getId()); System.out.println(" Current activities Id : " + processInstance.getActivityId()); }
5.8 Task Query
After the process is started, the person in charge of each task can inquire about the tasks that he needs to deal with at present, and the tasks that he inquires about are all the tasks to be done by the user.
// Query current individual tasks to be performed @Test public void findPersonalTaskList() { // Task-holders String assignee = "zhangsan"; // Create TaskService TaskService taskService = processEngine.getTaskService(); List<Task> list = taskService.createTaskQuery()// .processDefinitionKey("myholiday01")// .taskAssignee(assignee)//Query only the task holder's tasks .list(); for (Task task : list) { System.out.println(" Process examples id : " + task.getProcessInstanceId()); System.out.println("task id: " + task.getId()); System.out.println("Task-holders:" + task.getAssignee()); System.out.println("Task name:" + task.getName()); } }
5.9 Task Processing
Task-holders inquire about to-do tasks, select tasks for processing, and complete tasks.
// Complete tasks @Test public void completTask() { //Task id String taskId = "8305"; // Create TaskService TaskService taskService = processEngine.getTaskService(); //Complete tasks taskService.complete(taskId); System.out.println("Complete tasks id="+taskId); }