工作流的例子

news2024/11/28 5:38:03

工作流的例子

  • 目录
    • 概述
      • 需求:
    • 设计思路
    • 实现思路分析
      • 1.配置bean
      • 2.examples
      • 3.no bean
      • 4.activiti-api-basic-process-example
      • 5.task
    • spring
    • web
  • 参考资料和推荐阅读

Survive by day and develop by night.
talk for import biz , show your perfect code,full busy,skip hardness,make a better result,wait for change,challenge Survive.
happy for hardess to solve denpendies.

目录

在这里插入图片描述

概述

工作流的是一个非常常见的需求。

需求:

设计思路

实现思路分析

1.配置bean

@Bean
    public UserDetailsService myUserDetailsService() {

        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();

        String[][] usersGroupsAndRoles = {
                {"system", "password", "ROLE_ACTIVITI_USER"},
                {"reviewer", "password", "ROLE_ACTIVITI_USER"},
                {"admin", "password", "ROLE_ACTIVITI_ADMIN"},
        };

        for (String[] user : usersGroupsAndRoles) {
            List<String> authoritiesStrings = 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;

    }

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

2.examples

public class Content {

    private String body;
    private boolean approved;
    private List<String> tags;

    @JsonCreator
    public Content(@JsonProperty("body")String body, @JsonProperty("approved")boolean approved, @JsonProperty("tags")List<String> tags){
        this.body = body;
        this.approved = approved;
        this.tags = tags;
        if(this.tags == null){
            this.tags = new ArrayList<>();
        }
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public boolean isApproved() {
        return approved;
    }

    public void setApproved(boolean approved) {
        this.approved = approved;
    }

    public List<String> getTags() {
        return tags;
    }

    public void setTags(List<String> tags) {
        this.tags = tags;
    }

    @Override
    public String toString() {
        return "Content{" +
                "body='" + body + '\'' +
                ", approved=" + approved +
                ", tags=" + tags +
                '}';
    }
}

3.no bean

 @Bean
    public UserDetailsService myUserDetailsService() {

        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();

        String[][] usersGroupsAndRoles = {
                {"bob", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"},
                {"john", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"},
                {"hannah", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"},
                {"other", "password", "ROLE_ACTIVITI_USER", "GROUP_otherTeam"},
                {"system", "password", "ROLE_ACTIVITI_USER"},
                {"admin", "password", "ROLE_ACTIVITI_ADMIN"},
        };

        for (String[] user : usersGroupsAndRoles) {
            List<String> authoritiesStrings = 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;
    }

4.activiti-api-basic-process-example

 @Scheduled(initialDelay = 1000, fixedDelay = 1000)
    public void processText() {

        securityUtil.logInAs("system");

        String content = pickRandomString();

        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy HH:mm:ss");

        logger.info("> Processing content: " + content + " at " + formatter.format(new Date()));

        ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
                .start()
                .withProcessDefinitionKey("categorizeProcess")
                .withName("Processing Content: " + content)
                .withVariable("content", content)
                .build());
        logger.info(">>> Created Process Instance: " + processInstance);


    }

    @Bean
    public Connector processTextConnector() {
        return integrationContext -> {
            Map<String, Object> inBoundVariables = integrationContext.getInBoundVariables();
            String contentToProcess = (String) inBoundVariables.get("content");
            // Logic Here to decide if content is approved or not
            if (contentToProcess.contains("activiti")) {
                logger.info("> Approving content: " + contentToProcess);
                integrationContext.addOutBoundVariable("approved",
                        true);
            } else {
                logger.info("> Discarding content: " + contentToProcess);
                integrationContext.addOutBoundVariable("approved",
                        false);
            }
            return integrationContext;
        };
    }

5.task

 @Override
    public void run(String... args) {

        // Using Security Util to simulate a logged in user
        securityUtil.logInAs("bob");

        // Let's create a Group Task (not assigned, all the members of the group can claim it)
        // Here 'bob' is the owner of the created task
        logger.info("> Creating a Group Task for 'activitiTeam'");
        taskRuntime.create(TaskPayloadBuilder.create()
                .withName("First Team Task")
                .withDescription("This is something really important")
                .withCandidateGroup("activitiTeam")
                .withPriority(10)
                .build());

        // Let's log in as 'other' user that doesn't belong to the 'activitiTeam' group
        securityUtil.logInAs("other");

        // Let's get all my tasks (as 'other' user)
        logger.info("> Getting all the tasks");
        Page<Task> tasks = taskRuntime.tasks(Pageable.of(0, 10));

        // No tasks are returned
        logger.info(">  Other cannot see the task: " + tasks.getTotalItems());


        // Now let's switch to a user that belongs to the activitiTeam
        securityUtil.logInAs("john");

        // Let's get 'john' tasks
        logger.info("> Getting all the tasks");
        tasks = taskRuntime.tasks(Pageable.of(0, 10));

        // 'john' can see and claim the task
        logger.info(">  john can see the task: " + tasks.getTotalItems());


        String availableTaskId = tasks.getContent().get(0).getId();

        // Let's claim the task, after the claim, nobody else can see the task and 'john' becomes the assignee
        logger.info("> Claiming the task");
        taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(availableTaskId).build());


        // Let's complete the task
        logger.info("> Completing the task");
        taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(availableTaskId).build());


    }

spring

  @Override
    public void run(String... args) {
        securityUtil.logInAs("system");

        Page<ProcessDefinition> processDefinitionPage = processRuntime.processDefinitions(Pageable.of(0, 10));
        logger.info("> Available Process definitions: " + processDefinitionPage.getTotalItems());
        for (ProcessDefinition pd : processDefinitionPage.getContent()) {
            logger.info("\t > Process definition: " + pd);
        }

    }

    @Bean
    public MessageChannel fileChannel() {
        return new DirectChannel();
    }

    @Bean
    @InboundChannelAdapter(value = "fileChannel", poller = @Poller(fixedDelay = "1000"))
    public MessageSource<File> fileReadingMessageSource() {
        FileReadingMessageSource sourceReader = new FileReadingMessageSource();
        sourceReader.setDirectory(new File(INPUT_DIR));
        sourceReader.setFilter(new SimplePatternFileListFilter(FILE_PATTERN));
        return sourceReader;
    }

    @ServiceActivator(inputChannel = "fileChannel")
    public void processFile(Message<File> message) throws IOException {
        securityUtil.logInAs("system");

        File payload = message.getPayload();
        logger.info(">>> Processing file: " + payload.getName());

        String content = FileUtils.readFileToString(payload, "UTF-8");

        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy HH:mm:ss");

        logger.info("> Processing content: " + content + " at " + formatter.format(new Date()));

        ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
                .start()
                .withProcessDefinitionKey("categorizeProcess")
                .withName("Processing Content: " + content)
                .withVariable("content", content)
                .build());
        logger.info(">>> Created Process Instance: " + processInstance);

        logger.info(">>> Deleting processed file: " + payload.getName());
        payload.delete();

    }


    @Bean
    public Connector processTextConnector() {
        return integrationContext -> {
            Map<String, Object> inBoundVariables = integrationContext.getInBoundVariables();
            String contentToProcess = (String) inBoundVariables.get("content");
            // Logic Here to decide if content is approved or not
            if (contentToProcess.contains("activiti")) {
                logger.info("> Approving content: " + contentToProcess);
                integrationContext.addOutBoundVariable("approved",
                        true);
            } else {
                logger.info("> Discarding content: " + contentToProcess);
                integrationContext.addOutBoundVariable("approved",
                        false);
            }
            return integrationContext;
        };
    }

    @Bean
    public Connector tagTextConnector() {
        return integrationContext -> {
            String contentToTag = (String) integrationContext.getInBoundVariables().get("content");
            contentToTag += " :) ";
            integrationContext.addOutBoundVariable("content",
                    contentToTag);
            logger.info("Final Content: " + contentToTag);
            return integrationContext;
        };
    }

web

public class DemoApplication implements CommandLineRunner {

    private ProcessRuntime processRuntime;

    public DemoApplication(ProcessRuntime processRuntime) {
        this.processRuntime = processRuntime;
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }


    @PostMapping("/documents")
    public String processFile(@RequestBody String content) {

        ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
                                                                       .start()
                                                                       .withProcessDefinitionKey("categorizeProcess")
                                                                       .withVariable("fileContent",
                                                                                     content)
                                                                       .build());
        String message = ">>> Created Process Instance: " + processInstance;
        System.out.println(message);
        return message;
    }

    @GetMapping("/process-definitions")
    public List<ProcessDefinition> getProcessDefinition(){
        return processRuntime.processDefinitions(Pageable.of(0, 100)).getContent();
    }

    @Override
    public void run(String... args) {
    }

    @Bean
    public Connector processTextConnector() {
        return integrationContext -> {
            Map<String, Object> inBoundVariables = integrationContext.getInBoundVariables();
            String contentToProcess = (String) inBoundVariables.get("fileContent");
            // Logic Here to decide if content is approved or not
            if (contentToProcess.contains("activiti")) {
                integrationContext.addOutBoundVariable("approved",
                        true);
            } else {
                integrationContext.addOutBoundVariable("approved",
                        false);
            }
            return integrationContext;
        };
    }

    @Bean
    public Connector tagTextConnector() {
        return integrationContext -> {
            String contentToTag = (String) integrationContext.getInBoundVariables().get("fileContent");
            contentToTag += " :) ";
            integrationContext.addOutBoundVariable("fileContent",
                    contentToTag);
            System.out.println("Final Content: " + contentToTag);
            return integrationContext;
        };
    }

    @Bean
    public Connector discardTextConnector() {
        return integrationContext -> {
            String contentToDiscard = (String) integrationContext.getInBoundVariables().get("fileContent");
            contentToDiscard += " :( ";
            integrationContext.addOutBoundVariable("fileContent",
                    contentToDiscard);
            System.out.println("Final Content: " + contentToDiscard);
            return integrationContext;
        };
    }

}

参考资料和推荐阅读

[1]. https://github.com/Activiti/Activiti

欢迎阅读,各位老铁,如果对你有帮助,点个赞加个关注呗!~

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/3768.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

C++ 多态类型

多态 C在面向对象中&#xff0c;多态就是不同对象收到相同消息&#xff0c;执行不同的操作。在程序设计中&#xff0c;多态性是名字相同的函数&#xff0c;这些函数执行不同或相似的操作&#xff0c;这样就可以用同一个函数名调用不同内容的函数。简而言之“一个接口&#xff…

2022 国赛postgresql

安装postgresql配置postgresql [root@linux3 ~]# postgresql-setup --initdb //初始化数据库Initializing database in ‘/var/lib/pgsql/data’Initialized, logs are in /var/lib/pgsql/initdb_postgresql.log[root@linux3 ~]# systemctl enable postgresql.service Created …

澳洲最热门职业,护士排第一,医生竟然不如程序员?

2022澳洲最新的职业紧缺名单出炉了&#xff0c;令人惊讶的是护士竟然排行第一名&#xff0c;可见澳洲的医疗人力资源紧缺的问题。 既然人力资源紧缺&#xff0c;那么首当其冲的医生作为高学历且同属医疗行业的代表理应收到重视&#xff0c;然而令人意外的是&#xff0c;通过榜单…

Linux一篇入门(以Ubuntu为例)

一、Linux与Windows区别 Linux&#xff1a;无盘符&#xff0c;只有一个根目录&#xff08;/&#xff09; Windows&#xff1a;有盘符 二、目录相关常见命令 Linux命令格式&#xff1a; cmd -option parameter cdm命令&#xff0c;就是一个操作 parameter一般是要做的对象…

韩国程序员面试考什么?

大家好&#xff0c;我是老三&#xff0c;在G站闲逛的时候&#xff0c;从每日热门上&#xff0c;看到一个韩国的技术面试项目&#xff0c;感觉有点好奇&#xff0c;忍不住点进去看看。 韩国的面试都考什么&#xff1f;有没有国内的卷呢&#xff1f; 可以看到&#xff0c;有8.…

抽象类和接口

文章目录 前言 一、今日回顾 1.《高等数学》 2.阅读&#xff1a; 3.英语&#xff1a; 二、编程的那些事 1.引入库 2.读入数据 总结 前言 一、今日回顾 1.《高等数学》 2.阅读&#xff1a; 3.英语&#xff1a; 二、编程的那些事 1.抽象类的描述 在java中&#xff0…

一次函数与二次函数的联系

首先&#xff0c;无论是一次函数还是二次函数&#xff0c;都是函数&#xff0c;所以便可以从表达式&#xff0c;图像&#xff0c;函数的四个性质&#xff08;即有界性&#xff0c;单调性&#xff0c;奇偶性&#xff0c;周期性&#xff09;去看他们之间的联系 一次函数与二次函…

2022第8届中国大学生程序设计竞赛CCPC桂林站, 签到题4题

文章目录A. LilyM.Youth FinaleC.Array ConcatenationE.Draw a triangleA. Lily A. Lily time limit per test1 second memory limit per test512 megabytes inputstandard input outputstandard output They serve the purpose of changing hydrogen into breathable oxygen,…

MySQL数据库 -- 库和表的操作

关于数据库方面&#xff0c;还是需要多多练习的&#xff0c;否则很多指令不容易记住&#xff0c;所以大家也要在自己的电脑上多写写&#xff0c;熟悉熟悉~ 目录 库的操作 创建数据库 操纵数据库 查看数据库 显示创建语句 修改数据库 数据库的删除 数据库备份和恢复 …

重学数据库基础

幸福找到我&#xff0c;幸福说&#xff1a;“瞧这个诗人&#xff0c;他比我本人还要幸福” 一、数据库相关概念 数据库 存储数据的仓库&#xff0c;数据是有组织的进行存储英文&#xff1a;DataBase&#xff0c;简称 DB 数据库管理系统 管理数据库的大型软件英文&#xff1a;Da…

CSI室内指纹定位——相关通信名词解释

目录 1、无线信道 2、时域与频域 3、信道频率响应&#xff08;Channel Frequency Response,CFR&#xff09; 4、信道冲激响应&#xff08;Channel Impulse Response, CIR&#xff09; 5、信道带宽 6、带宽 7、子载波 9、波长 10、频率 11、振幅 12、相位 13、相位差…

高数值孔径(NA)物镜的聚焦分析

1. 摘要 高NA物镜广泛用于光刻&#xff0c;显微等技术。因此&#xff0c;聚焦仿真中考虑光的矢量性质至关重要。VirtualLab可以非常便捷地对此类镜头进行光线追迹和场追迹分析。通过场追迹&#xff0c;可以清楚地观察由于矢量效应引起的聚焦光斑失对称现象。利用相机探测器和电…

第十四届蓝桥杯(Web应用开发)模拟赛1期-大学组

数据类型检测 请看这篇数据类型检测 渐变色背景生成器 html <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8" /><meta http-equiv"X-UA-Compatible" content"IEedge" /><meta name&…

java面试官:程序员,请你告诉我是谁把公司面试题泄露给你的?

前情提要&#xff1a; 面试官&#xff1a;你好&#xff01;请先做一下自我介绍&#xff01; 程序员&#xff1a;balabalabala... 前戏先过了.... 面试官&#xff1a;先介绍SpringCloud核心组件及其作用 程序员&#xff1a;SpringCloud由以下5个核心组件构成...另外&#x…

MySQL事务基本操作(方式1)

在观看本文前 你需要了解什么事事务 如果不太了解 可以先查看我的文章 MySQL事务基本概念 首先 我们这里有一张 staff 用户表 然后来一波 减岁交易大法 赵敏买个了 黄飞鸿十年时光 那么就是 先查询确认赵敏加上十岁不会过百 将赵敏年龄加十岁 确认黄飞鸿减去十岁不会小于零 然…

Java项目(三)-- SSM开发社交网站(9)--后台图书管理功能

后台图书管理功能 富文本编辑器wangEditor 基于javascript与css开发是Web富文本编辑器&#xff0c;轻量、简洁、易用、开源免费。 代码演示 我们在test.ftl中添加富文本编辑器演示下 <!DOCTYPE html> <html lang"en"> <head><meta charset&…

CMake中string的使用

CMake中的string命令用于字符串操作,其格式如下&#xff1a; Search and Replacestring(FIND <string> <substring> <out-var> [...])string(REPLACE <match-string> <replace-string> <out-var> <input>...)string(REGEX MATCH &l…

【数据库Redis】Redis五种基本数据结构以及三种配置方式——默认配置、运行配置、配置文件启动

文章目录一、初识Redis1.1 了解Redis1.2 Redis特性1.3 Redis使用场景Redis不适合场景1.4 用好Redis的建议1.5 正确安装并启动Redis在Linux上安装Redis在Windows上安装Redis配置、启动、操作、关闭Redis1)、启动Redis2)、Redis命令行客户端3)、停止Redis服务1.6 Redis重大版本一…

JVM(十四)—— StringTable

JVM&#xff08;十四&#xff09;—— StringTableString的基本特性String的内存分配字符串拼接intern方法常见面试题&#xff1a;到底创建了几个String对象String的基本特性 作为一名Java程序员肯定少不了和 String打交道&#xff0c;使用方法就是将字符串用一对""…

SpringCloud 远程调用

目录 1. SpringCloud 2. Nacos 3. 远程通信 3.1 创建公共子模块 (nacos_commons) 3.1.1 DTO对象 3.2 父项目引入子项目 (nacos_commons) 打成的jar包 3.3 父项目指向子项目 (nacos_commons) 为儿子 3.4 子项目 (nacos_provider) 3.5 子项目 (nacos_consumer) …