基于SpringBoot的jbpm7环境搭建 您所在的位置:网站首页 JBPM使用详解 基于SpringBoot的jbpm7环境搭建

基于SpringBoot的jbpm7环境搭建

2024-06-02 18:28| 来源: 网络整理| 查看: 265

基于SpringBoot的jbpm7环境搭建 1 创建SpringBoot 项目

pom.xml如下:

4.0.0 com.xxxx springboot-demo 0.0.1-SNAPSHOT org.springframework.boot spring-boot-starter-parent 2.1.4.RELEASE mysql mysql-connector-java org.kie kie-server-spring-boot-starter-jbpm 7.31.0.Final tomcat naming-factory-dbcp 5.5.15 org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-maven-plugin

application.properties配置文件如下:

server.port=8080 server.servlet.context-path=/spring #datasource configuration spring.datasource.username=root spring.datasource.password=1234 spring.datasource.url=jdbc:mysql://localhost:3307/jbpm?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Chongqing #hibernate configuration spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.properties.hibernate.show_sql=true spring.jpa.properties.hibernate.hbm2ddl.auto=update #Entity scan packages spring.jpa.properties.entity-scan-packages=application.entity spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl #transaction manager configuration spring.jta.narayana.transaction-manager-id=1 logging.level.com.arjuna.ats.jdbc=ERROR 2 创建jbpm配置文件 package application.config; import javax.persistence.EntityManagerFactory; import org.jbpm.runtime.manager.impl.RuntimeEnvironmentBuilder; import org.jbpm.services.task.identity.DBUserGroupCallbackImpl; import org.kie.api.io.ResourceType; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.manager.RuntimeEngine; import org.kie.api.runtime.manager.RuntimeEnvironment; import org.kie.api.runtime.manager.RuntimeManager; import org.kie.api.runtime.manager.RuntimeManagerFactory; import org.kie.api.task.TaskService; import org.kie.internal.io.ResourceFactory; import org.kie.internal.runtime.manager.context.EmptyContext; import org.kie.internal.task.api.UserGroupCallback; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; @Configuration public class JbpmConfig { @Bean RuntimeEnvironment runtimeEnvironment(EntityManagerFactory entityManagerFactory) { RuntimeEnvironment runtimeEnvironment = RuntimeEnvironmentBuilder.Factory.get() .newDefaultBuilder().entityManagerFactory(entityManagerFactory) //Test.bpmn放置于resource文件夹下 .addAsset(ResourceFactory.newClassPathResource("Test.bpmn"), ResourceType.BPMN2) .get(); return runtimeEnvironment; } @Bean RuntimeManager runtimeManager(RuntimeManagerFactory runtimeManagerFactory,RuntimeEnvironment runtimeEnvironment) { RuntimeManager runtimeManager = runtimeManagerFactory.newSingletonRuntimeManager(runtimeEnvironment); return runtimeManager; } @Bean RuntimeEngine runtimeEngine(RuntimeManager runtimeManager) { RuntimeEngine runtimeEngine = runtimeManager.getRuntimeEngine(EmptyContext.get()); return runtimeEngine; } @Bean KieSession kieSession(RuntimeEngine runtimeEngine) { KieSession kieSession = runtimeEngine.getKieSession(); return kieSession; } @Bean TaskService taskService(RuntimeEngine runtimeEngine) { TaskService taskService = runtimeEngine.getTaskService(); return taskService; } //userGroupCallback用于判断用户是否存在,组是否存在,找到用户所属的组,默认已经配置了SpringSecurityUserGroupCallback作为userGroupCallback的bean,但是我们希望使用自己的数据库表来进行判断,所以配置DBUserGroupCallbackImpl作为 userGroupCallback的bean,需要使用jbpm.usergroup.callback.properties来配置 @Bean @DependsOn("jndiDataSource") UserGroupCallback userGroupCallback() { return new DBUserGroupCallbackImpl(true); } }

jbpm.usergroup.callback.properties配置如下:

#jndi name db.ds.jndi.name=java:comp/env/jdbc/kpi #判断用户是否存在 db.user.query=select username from kpi_user where username=? #判断用户所属的组 db.user.roles.query=select r.rolename from kpi_role r join kpi_user_role ur on r.id=ur.rid join kpi_user u on u.id = ur.uid where u.username=? #判断组是否存在 db.roles.query=select rolename from kpi_role where rolename=?

这些配置信息会被加载到DBUserGroupCallback中,当需要进行判断用户是否存在时,就用db.user.query获取的sql来查询数据库,根据result判断用户是否存在。

配置jndi datasource

package application.config; import javax.naming.NamingException; import javax.sql.DataSource; import org.apache.catalina.Context; import org.apache.catalina.startup.Tomcat; import org.apache.tomcat.util.descriptor.web.ContextResource; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.embedded.tomcat.TomcatWebServer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import org.springframework.jndi.JndiObjectFactoryBean; @Configuration public class TomcatConfig { @Bean public TomcatServletWebServerFactory tomcatFactory() { return new TomcatServletWebServerFactory() { @Override protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) { tomcat.enableNaming(); return super.getTomcatWebServer(tomcat); } @Override protected void postProcessContext(Context context) { ContextResource resource = new ContextResource(); resource.setType(DataSource.class.getName()); resource.setName("jdbc/kpi"); resource.setProperty("factory", "org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"); resource.setProperty("driverClassName", "com.mysql.cj.jdbc.Driver"); resource.setProperty("url", "jdbc:mysql://localhost:3307/jbpm?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Chongqing"); resource.setProperty("username", "root"); resource.setProperty("password", "1234"); context.getNamingResources().addResource(resource); } }; } @Bean(destroyMethod="") @DependsOn("tomcatFactory") public DataSource jndiDataSource() throws IllegalArgumentException, NamingException { JndiObjectFactoryBean bean = new JndiObjectFactoryBean(); bean.setJndiName("java:comp/env/jdbc/kpi"); bean.setProxyInterface(DataSource.class); bean.setLookupOnStartup(false); bean.afterPropertiesSet(); return (DataSource) bean.getObject(); } } 3 创建用户表,角色表,用户角色关系表 /* SQLyog Community v13.0.1 (64 bit) MySQL - 5.6.19-log : Database - jbpm ********************************************************************* */ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; CREATE DATABASE /*!32312 IF NOT EXISTS*/`jbpm` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `jbpm`; /*Table structure for table `kpi_role` */ DROP TABLE IF EXISTS `kpi_role`; CREATE TABLE `kpi_role` ( `id` int(11) NOT NULL AUTO_INCREMENT, `rolename` varchar(255) NOT NULL, `staus` int(11) NOT NULL, `status` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; /*Data for the table `kpi_role` */ insert into `kpi_role`(`id`,`rolename`,`status`) values (1,'Administrators',1,0), (2,'PM',1), (3,'SVP',1), (4,'EVP',1), (5,'Admin',1); /*Table structure for table `kpi_user` */ DROP TABLE IF EXISTS `kpi_user`; CREATE TABLE `kpi_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `age` int(11) DEFAULT NULL, `status` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; /*Data for the table `kpi_user` */ insert into `kpi_user`(`id`,`username`,`password`,`age`,`status`) values (1,'Nero','$2a$10$6NQ7ZWOGHT.W7JhlIa6hQOpABmGlBW7Essr5m78Pu.S3Gav7rha/K',23,1), (2,'JOJO','$2a$10$6NQ7ZWOGHT.W7JhlIa6hQOpABmGlBW7Essr5m78Pu.S3Gav7rha/K',17,1), (3,'Test','$2a$10$6NQ7ZWOGHT.W7JhlIa6hQOpABmGlBW7Essr5m78Pu.S3Gav7rha/K',99,1), (4,'Administrator','$2a$10$6NQ7ZWOGHT.W7JhlIa6hQOpABmGlBW7Essr5m78Pu.S3Gav7rha/K',100,1); /*Table structure for table `kpi_user_role` */ DROP TABLE IF EXISTS `kpi_user_role`; CREATE TABLE `kpi_user_role` ( `id` int(11) NOT NULL AUTO_INCREMENT, `uid` int(11) NOT NULL, `rid` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `uid` (`uid`), KEY `rid` (`rid`), CONSTRAINT `kpi_user_role_ibfk_2` FOREIGN KEY (`rid`) REFERENCES `kpi_role` (`id`), CONSTRAINT `kpi_user_role_ibfk_1` FOREIGN KEY (`uid`) REFERENCES `kpi_user` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8; /*Data for the table `kpi_user_role` */ insert into `kpi_user_role`(`id`,`uid`,`rid`) values (1,1,1), (2,2,3), (3,3,4), (4,1,2), (5,1,3), (6,2,4), (7,2,1), (8,1,5), (9,2,5), (10,3,5), (11,4,1); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

此处的表用作userGroupCallback查询用户和组是否存在,以及作为spring scurity的数据库认证的实体表,在创建这些表之前要使用jbpm官方给的sql创建jbpm初始化表来支持jbpm的使用。

4 spring security的配置

基于上面的表,创建实体类

User

package application.entity; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import com.fasterxml.jackson.annotation.JsonIgnore; @Entity @Table(name="kpi_user") public class User implements UserDetails{ /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; private String username; private String password; private int age; private int status; @ManyToMany(cascade = {CascadeType.PERSIST,CascadeType.MERGE,CascadeType.REMOVE}, fetch = FetchType.EAGER) @JoinTable( name="kpi_user_role", joinColumns=@JoinColumn(name="uid",referencedColumnName="id"), inverseJoinColumns=@JoinColumn(name="rid") ) @JsonIgnore private List roles = new ArrayList(); public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public List getRoles(){ return roles; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", password=" + password + ", age=" + age + ", status=" + status + "]"; } @Override public Collection getAuthorities() { // TODO Auto-generated method stub for(Role role:roles) { role.setRolename("ROLE_"+role.getRolename()); System.out.println(role.getAuthority()); } return roles; } @Override public boolean isAccountNonExpired() { // TODO Auto-generated method stub return true; } @Override public boolean isAccountNonLocked() { // TODO Auto-generated method stub return true; } @Override public boolean isCredentialsNonExpired() { // TODO Auto-generated method stub return true; } @Override public boolean isEnabled() { // TODO Auto-generated method stub return true; } }

Role

package application.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.springframework.security.core.GrantedAuthority; @Entity @Table(name="kpi_role") public class Role implements GrantedAuthority{ /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; private String rolename; private int status; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getRolename() { return rolename; } public void setRolename(String rolename) { this.rolename = rolename; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } @Override public String toString() { return "Role [id=" + id + ", rolename=" + rolename + ", status=" + status + "]"; } @Override public String getAuthority() { // TODO Auto-generated method stub return rolename; } }

UserRole

package application.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="kpi_user_role") public class UserRole { @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; private int rid; private int uid; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getRid() { return rid; } public void setRid(int rid) { this.rid = rid; } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } @Override public String toString() { return "UserRole [id=" + id + ", rid=" + rid + ", uid=" + uid + "]"; } }

创建 UserRepository,RoleRepository,UserRoleRepository 都继承JpaRepository

UserRepository

package application.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import application.entity.User; @Repository public interface UserRepository extends JpaRepository{ @Query("from User where username=?1") public User findUserByName(String username); }

RoleRepository

package application.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import application.entity.Role; @Repository public interface RoleRepository extends JpaRepository{ }

UserRoleRepository

package application.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import application.entity.UserRole; @Repository public interface UserRoleRepository extends JpaRepository{ }

配置userService实现UserDetailService

package application.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import application.repository.UserRepository; @Service public class UserService implements UserDetailsService{ @Autowired UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // TODO Auto-generated method stub return userRepository.findUserByName(username); } }

配置security configuration

package application.config; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.access.AccessDeniedException; 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.Authentication; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import application.service.UserService; @Configuration("kieServerSecurity") @EnableWebSecurity public class DefaultWebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserService userService; @Bean public PasswordEncoder passwordEncoder() { //使用BCryptPasswordEncoder对密码进行编码,所有用户密码均为123456 PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); //编码后为 $2a$10$ZxaV8wD2gDSLokqVK9lJW.O9qqK07LEkcKV6KaUtCSZk0EqI2pXyO System.out.println("123456 密码编码: "+passwordEncoder.encode("123456")); return passwordEncoder; } @Override protected void configure(HttpSecurity http) throws Exception { // TODO Auto-generated method stub http.cors().and().csrf().disable().authorizeRequests().antMatchers("/kpi/index","/kpi/error").permitAll().antMatchers("/kpi/**") //.hasRole("Administrators") .authenticated() .and().exceptionHandling().accessDeniedHandler(new AccessDeniedHandler() { @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException arg2) throws IOException, ServletException { response.sendRedirect("/spring/kpi/error"); } }).and().httpBasic() .and().headers().frameOptions().disable().and().formLogin().usernameParameter("username").passwordParameter("password").loginProcessingUrl("/login").and() .logout().logoutUrl("/logout").logoutSuccessHandler(new LogoutSuccessHandler() { @Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication arg2) throws IOException, ServletException { response.sendRedirect("/spring/kpi/index"); } }); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userService).passwordEncoder(passwordEncoder()); } }

使用 Bussiness central 创建Test.bpmn,并导入放到resource文件夹下

在这里插入图片描述 在这里插入图片描述

创建测试用的controller

package application.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import org.kie.api.runtime.KieSession; import org.kie.api.task.TaskService; import org.kie.api.task.model.TaskSummary; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import application.entity.User; import application.repository.UserRepository; @RestController @RequestMapping(value = "/kpi") public class HelloController { @Autowired private KieSession kieSession; @Autowired private TaskService taskService; @Autowired private UserRepository userRepository; @RequestMapping(value="index") public String Index() { return "Welcome, Pleas Login!"; } @RequestMapping(value="error") public String error() { return "User have no right to access!"; } @PostMapping(value = "startProcess") public Long startProcess(String userId) { Map data = new HashMap(16); data.put("Manager", userId); return kieSession.startProcess("Test", data).getId(); } @GetMapping(value="getTask") public List getTask() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); return taskService.getTasksAssignedAsPotentialOwner(auth.getName(), "en_US"); } @PostMapping("startTask") public void startTask(String userId,Long taskId) { taskService.start(taskId, userId); } @PostMapping("completeTask") public void completeTask(String userId,Long taskId) { taskService.complete(taskId, userId, null); } @PostMapping("claim") public void calim(String userId,Long taskId) { taskService.claim(taskId, userId); } //用于测试 jpa是否配置生效 @GetMapping("getUserByUsername/{username}") public User getUserName(@PathVariable("username") String username) { User user=userRepository.findUserByName(username); System.out.println(userRepository.getClass()); return user; } }

使用postman进行测试

要先进行登陆,否则会提示没有认证 在这里插入图片描述

login 在这里插入图片描述

startProcess

在这里插入图片描述

getTask

在这里插入图片描述

startTask and completeTask 没有返回参数 在这里插入图片描述 在这里插入图片描述

再次查看任务列表时id25的任务已经处理完成,就查找不到了

在这里插入图片描述



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有