详解springBoot集成activiti7,工作流实战案例(三)

2021年1月23日 32点热度 0条评论 来源: 小伙子。

快速使用IDEA搭建SpringBoot项目,集成Activiti7(一) 

详解springBoot集成activiti7,使用actiBPM绘制流程图(二)

过程分析:

  1. 部署流程
  2. 启动一个流程实例
  3. 查询当前流程中等待执行的任务
  4. 处理任务
  5. 流程结束

用到activiti的service(ps:记得注入):

  1. RepositoryService
  2. RuntimeService
  3. TaskService
    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

1.部署流程

    /**
     * 部署流程
     */
    public void prepare() {
        // 创建一个部署对象
        Deployment deployment = repositoryService.createDeployment ()
                .name ("请假流程")
                .addClasspathResource ("processes/test_bpmn20.xml")
                .addClasspathResource ("processes/test.png")
                .deploy ();
        System.out.println ("部署ID:" + deployment.getId ());
        System.out.println ("部署名称:" + deployment.getName ());
    }

2.启动一个流程实例

    /**
     * 启动流程实例
     */
    public void startProcess() {
        String processDefinitionKey = "test01";
        Map<String, Object> map = new HashMap<> ();
        
        //使用UEL 表达式设置
        
        // 学生填写申请单    Assignee:${student}
        map.put ("student", "lucy");

        // 班主任审批    Assignee:${teacher}
        map.put ("teacher", "jack");

        ProcessInstance instance = runtimeService.startProcessInstanceByKey (processDefinitionKey, map);
        System.out.println ("流程实例ID:" + instance.getId ());
        System.out.println ("流程定义ID:" + instance.getProcessDefinitionId ());
    }

3.任务查询

    /**
     * 任务查询
     */
    public List<String> searchTask() {
        //流程启动后,各各任务的负责人就可以查询自己当前需要处理的任务,查询出来的任务都是该用户的待办任务。
        List<Task> list = taskService.createTaskQuery ()
                //流程实例key
                .processDefinitionKey ("test01")
                //查询谁的任务
                //.taskAssignee("")
                .list ();
        List<String> idList = new ArrayList<String> ();

        for (Task task : list) {
            idList.add (task.getId ());
            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 ());
            System.out.println ("执行对象ID:" + task.getExecutionId ());
            System.out.println ("流程定义ID:" + task.getProcessDefinitionId ());
        }

        return idList;

    }

4.处理任务

    /**
     * 处理任务
     */
    public void disposeTask(List<String> list) {
        for (String id : list) {
            // 任务id
            taskService.complete (id);
            System.out.println ("处理任务id:" + id);
        }
    }

5.测试请假流程

    @GetMapping("/run")
    public void run() {

        // 1.部署流程
        prepare ();

        // 2.启动一个流程实例
         startProcess ();

        // 3.任务查询
         List list = searchTask ();

        // 4.处理任务
         disposeTask (list);
    }

6.浏览器访问127.0.0.1:8080/run

 

出现Caused by: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: 3 字节的 UTF-8 序列的字节 3 无效。

异常说明字符编码乱码,检查test.bpmn,test_bpmn20.xml文件是否出现乱码

这时候的test.bpmn可以删掉(做个备份吧!),IDEA保存之后就会编码错误,很头疼!

被拦截了,要求登陆,原因是activiti7使用了Security,需要认证

7.Security的配置,直接拿官方的实例,与启动类DemoApplication同级目录下

/*
 * Copyright 2018 Alfresco, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.activiti.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Set up some users and groups that we can use when interacting with the process engine API.
 * We use the testuser in the process definition so we need to include this user.
 *
 * We also enable Web security so we can build a simple ReST API that uses the Process Engine Java API. We need
 * to be authenticated with a user that has the role ROLE_ACTIVITI_USER to be able to use the API.
 */
@Configuration
@EnableWebSecurity
public class DemoApplicationConfiguration extends WebSecurityConfigurerAdapter {

    private Logger logger = LoggerFactory.getLogger(DemoApplication.class);

    @Override
    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService());
    }

    @Bean
    public UserDetailsService myUserDetailsService() {

        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();

        String[][] usersGroupsAndRoles = {
                {"mbergljung", "1234", "ROLE_ACTIVITI_USER", "GROUP_activitiTraining"},
                {"testuser", "1234", "ROLE_ACTIVITI_USER", "GROUP_activitiTraining"},
                {"system", "1234", "ROLE_ACTIVITI_USER"},
                {"admin", "1234", "ROLE_ACTIVITI_ADMIN"},
        };

        for (String[] user : usersGroupsAndRoles) {
            List<String> authoritiesStrings = Arrays.asList(Arrays.copyOfRange(user, 2, user.length));
            logger.info("> Registering new user: " + user[0] + " with the following Authorities[" + authoritiesStrings + "]");
            inMemoryUserDetailsManager.createUser(new User(user[0], passwordEncoder().encode(user[1]),
                    authoritiesStrings.stream().map(s -> new SimpleGrantedAuthority(s)).collect(Collectors.toList())));
        }


        return inMemoryUserDetailsManager;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .httpBasic();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

8.继续访问,浏览器填写密码请看 

访问成功控制台输出:

ps:学生填写完成,任务交给班主任,等待班主任审批,班主任审批完成,流程结束。再次执行任务查询即是完成班主任审批任务。 

最后,一个简单的activiti7的实例就完成了

    原文作者:小伙子。
    原文地址: https://blog.csdn.net/weixin_44096448/article/details/103615512
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。