Configuring jBPM to use PostgreSQL Database

This tutorial discusses how to configure jBPM to use PostgreSQL as database to store process data.

jBPM out of the box uses H2 database to store the state of processes using a file located under $JBOSS_HOME/standalone/data/jbpm-db. In order to switch to another database, you can use any of the following scripts which are available in $JBOSS_HOME/bin.

In order to swtich to PostgreSQL:

$ ./jboss-cli.sh --file=jbpm-postgres-config.cli      (Unix / Linux)

The above commands needs to be executed when the server is stopped as an embedded server process will be used to update the configuration.

These scripts assume that database is installed and some default configuration is present:

  • host → localhost
  • port → 5432
  • database name → jbpm
  • user name → jbpm

Changing jBPM to PostgreSQL

As an example, we will show how to change the default database to PostgreSQL. Start PostgreSQL for example with Docker:

 docker run --ulimit memlock=-1:-1 -it --rm=true --memory-swappiness=0 --name jbpm -e POSTGRES_USER=jbpm -e POSTGRES_PASSWORD=jbpm -e POSTGRES_DB=jbpm -p 5432:5432 postgres

Then, run the jbpm-postgres-config.cli

$ ./jboss-cli.sh --file=jbpm-postgres-config.cli      (Unix / Linux)

Now start jBPM:

$ ./standalone.sh

As you can see from the XML configuration, the datasource named “jBPMXADS” has been added:

  <xa-datasource jndi-name="java:jboss/datasources/jBPMDS" pool-name="jBPMXADS">
                    <xa-datasource-property name="ServerName">
                        localhost
                    </xa-datasource-property>
                    <xa-datasource-property name="PortNumber">
                        5432
                    </xa-datasource-property>
                    <xa-datasource-property name="DatabaseName">
                        jbpm
                    </xa-datasource-property>
                    <xa-datasource-class>org.postgresql.xa.PGXADataSource</xa-datasource-class>
                    <driver>postgres</driver>
                    <security>
                        <user-name>jbpm</user-name>
                        <password>jbpm</password>
                    </security>
                    <validation>
                        <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLValidConnectionChecker"/>
                        <validate-on-match>true</validate-on-match>
                        <background-validation>true</background-validation>
                        <background-validation-millis>120000</background-validation-millis>
                        <exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLExceptionSorter"/>
                    </validation>
                </xa-datasource>
                <drivers>
                    <driver name="h2" module="com.h2database.h2">
                        <xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
                    </driver>
                    <driver name="postgres" module="org.postgres">
                        <xa-datasource-class>org.postgresql.xa.PGXADataSource</xa-datasource-class>
                    </driver>
                </drivers>

You can also log into PostgreSQL and check that tables have been created:

jbpm=# \dt
                    List of relations
 Schema |              Name              | Type  | Owner
 public | attachment                     | table | jbpm
 public | audittaskimpl                  | table | jbpm
 public | bamtasksummary                 | table | jbpm
 public | booleanexpression              | table | jbpm
 public | casefiledatalog                | table | jbpm
 public | caseidinfo                     | table | jbpm
 public | caseroleassignmentlog          | table | jbpm
 public | content                        | table | jbpm
 public | contextmappinginfo             | table | jbpm
 public | correlationkeyinfo             | table | jbpm
 public | correlationpropertyinfo        | table | jbpm
 public | deadline                       | table | jbpm
 public | delegation_delegates           | table | jbpm
 public | deploymentstore                | table | jbpm
 public | email_header                   | table | jbpm
 public | errorinfo                      | table | jbpm
 public | escalation                     | table | jbpm
 public | eventtypes                     | table | jbpm
 public | executionerrorinfo             | table | jbpm
 public | i18ntext                       | table | jbpm
 public | nodeinstancelog                | table | jbpm
 public | notification                   | table | jbpm
 public | notification_bas               | table | jbpm
 public | notification_email_header      | table | jbpm
 public | notification_recipients        | table | jbpm
 public | organizationalentity           | table | jbpm
 public | peopleassignments_bas          | table | jbpm
 public | peopleassignments_exclowners   | table | jbpm
 public | peopleassignments_potowners    | table | jbpm
 public | peopleassignments_recipients   | table | jbpm
 public | peopleassignments_stakeholders | table | jbpm
 public | processinstanceinfo            | table | jbpm
 public | processinstancelog             | table | jbpm
 public | querydefinitionstore           | table | jbpm
 public | reassignment                   | table | jbpm
 public | reassignment_potentialowners   | table | jbpm
 public | requestinfo                    | table | jbpm
 public | sessioninfo                    | table | jbpm
 public | task                           | table | jbpm
 public | task_comment                   | table | jbpm
 public | taskdef                        | table | jbpm
 public | taskevent                      | table | jbpm
 public | taskvariableimpl               | table | jbpm
 public | variableinstancelog            | table | jbpm
 public | workiteminfo                   | table | jbpm
(45 rows)

Configuring Applications to use jBPM with PostgreSQL

Let’s see how to configure jBPM embedded in your applications. When using Spring Boot it’s pretty easy. What you need is to add the JDBC driver in your configuration:

<dependency>
    <groupId>org.kie</groupId>
    <artifactId>kie-server-spring-boot-starter</artifactId>
    <version>${version.org.kie}</version>
</dependency>

<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
</dependency>

Then, you can configure the Datasource connectivity in your application.properties

server.address=0.0.0.0
server.port=8090

cxf.path=/rest

#kie server config
kieserver.serverId=business-application-service
kieserver.serverName=business-application-service
kieserver.location=http://localhost:8090/rest/server
#kieserver.controllers=


#kie server capabilities
kieserver.drools.enabled=true
kieserver.dmn.enabled=true
kieserver.jbpm.enabled=true
kieserver.jbpmui.enabled=true
kieserver.casemgmt.enabled=true


#jbpm configuration
jbpm.executor.enabled=false
#jbpm.executor.retries=5
#jbpm.executor.interval=3
#jbpm.executor.threadPoolSize=1
#jbpm.executor.timeUnit=SECONDS

spring.datasource.username=jbpm
spring.datasource.password=jbpm
spring.datasource.url=jdbc:postgresql://localhost:5432/jbpm
spring.datasource.driver-class-name=org.postgresql.xa.PGXADataSource

#hibernate configuration
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.show_sql=false
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

#transaction manager configuration
spring.jta.narayana.transaction-manager-id=1

#banner
spring.banner.location=classpath:banner.txt

narayana.transaction-manager-id=1
narayana.default-timeout=120
narayana.dbcp.enabled=true

As an example, see the following jBPM application which requires a PostgreSQL database connection: https://github.com/fmarchioni/mastertheboss/tree/master/jbpm/business-application-postgresql

Create your first process with jBPM 6 Web designer

In this tutorial we will learn how to design a process from scratch using the jBPM6 Web designer or the business-central of its supported version, named Red Hat JBoss BPM

Prerequisites: You have an installed jBPM 6 or the supported version Red Hat JBoss BPM 6.

Reach the Web console:

Authoring a Process

In order to create a new process you have at first to define an Organizational Unit for it. From the top menu go to Authoring | Administration| Organizational Units | Manage Organizational Units.

Click Add to create a new Organizational unit, and provide a Name for it, the user in charge to admin the unit, and the Maven group name:

Next step will be adding a Repository. jBPM 6 uses an internal Git repository to store your projects. In order to create it, navigate through the menus, and go to Authoring | Administration | Repositories | New Repository. Enter a name for the repository, choose the organization unit and create the repository.

Create your process with the Web designer

It’s time to create your first process. Go to Authoring | Project Authoring. Select New Item and choose Project. At first you will choose the Project name:

Next enter the Project General settings as indicated in this picture:

Click on Finish. Now we will add our first process. Select New Item | Business Process and enter a name for the business process;

Now, the business console will show you the process modeler for designing your business processes.

The process modeler is made up of the following 4 parts:

  1. On the left side the Object library contains all the BPM components. Drag and drop them to include them in the process
  2. The Workspace on the center contains the process model
  3. The Property window on the right can be used to configure properties of the BPM components
  4. The Upper toolbar contains some typical options for saving, copy and past, export/import of the process

Building Your First BPM Application

We will now define a simple process which will contain a HumanTask to be completed and a couple of Script Task to debug the outcome of the status. Here is our process:

First of all, we have defined one Process variable named “approved” that will be later used to collect information from an Human Task.

Next, the process contains the Human Task which has been assigned to the bpmnAdmin user:

In the assignment window (you can reach it from the Property window of the Task), you can map in/out variables generated in the Human task. In our example, we are collecting one Boolean, the approved variable, which will be then stored in the corresponding Process variable.

The gateways are a basic example on how to control the process flow. It can lead to two different paths: the first one will be used when the variable approved is “true”:

On the other hand, when approved is “false”, the second path will be chosen:

The Script tasks are just there to debug our Process, including a System.out inside it:

Deploy and Run the process

Go to Authoring, click on Open Project Editor. Click Build & Deploy. Check that the build and deploy was successful, next move to Process Management | Process definitions. You should find the Process Definition :

Click on Start in order to launch a new instance of the Process. You will be able to enter some values for the process variables if any. The process will be visible in the Process Instances UI. Next move to the Tasks menu and verify that you have in charge the Task (if not check that the Actor you have assigned is the same user you have used for logging in the business console):

At first start the Task:

 Next fill up the auto-generated form with the approved parameter and click on Complete.

Now the process will end, verify from the Server logs that the process has gone through the right path:

12:24:23,995 INFO [stdout] (http-/127.0.0.1:8080-17) Process approved!!

That’s all! In the next tutorial we will learn how to fire and control your Process instances through the REST API.

Getting started with JBPM 6 Remote Client API

{loadposition william}

In this article we will show how to create a standalone application that access jBPM 6 to start a process and handle its tasks.

We already talked about jBPM 6 and a Web Application using it: Developing a jBPM 7 Web application example

We will now learn how to manage processes and tasks remotely using the REST API. Thanks to the jBPM 6 REST API it is possible to manage tasks, process, create process instances, and other actions using a simple API which merely requires the use of a simple HTTP client library. When you start jbpm 6, you can access a summary of all available REST API functionalities by accessing the url http://localhost:8080/business-central/rest-api.jsp:

A Java API for the REST interface

If you don’t like to manually create HTTP requests to access jBPM remotely, no worries! There’s a Java API that is aimed to wrap the HTTP requests for you. The entry point of this API is the class RuntimeEngine, and you can access get an instance of it by using the class RemoteRuntimeEngineFactory as follows:

// Setup the factory class with the necessarry information to communicate with the REST services
RuntimeEngine engine = RemoteRuntimeEngineFactory.newRestBuilder()
.addUrl(serverRestUrl)
.addTimeout(5)
.addDeploymentId(deploymentId)
.addUserName(user)
.addPassword(password)
// if you're sending custom class parameters, make sure that
// the remote client instance knows about them!
.addExtraJaxbClasses(MyType.class)
.build();

Now you have access to KieSession, TaskService and AuditService remote interfaces and you are able to perform remote calls using pure Java code without having to care about XML/JSON parsing and how to manage HTTP connections with the remote jbpm server. To use the remote API you must have the maven dependency kie-remote for jBPM 6.3:

<dependency>
    <groupId>org.kie.remote</groupId>
    <artifactId>kie-remote-client</artifactId>
    <version>6.3.0.Final</version>
</dependency>

Our Sample process

To show the API in action we will create and deploy a project in Kie Workbench as it was explained in the article Introduction to jBPM 6. The process we are going to use is the rewards-basic with a few more nodes, see:

 This process basically accepts a String variable that contains the name of an employee that should receive a reward. If approved by the PM of the project and for the HR, the employee will receive the reward. Of course, this is a simple process to help us to show the remote API functionalities. We could increase it for example by adding a task to send email instead printing it in the console, or make a Web Service call, etc. We could also use complex types instead String or more detailed approval process, but for the sake of simplicity, we keep it using primitive types.

The process basically has two variables of type String for the employeeName and result. The employeeName it is set when starting the process (passed as a parameter) and the result value will depends on the approval flow. It also has two boolean variables: pmApproval and hrApproval. These variables will be set as a parameter resulting from the human tasks completion, which means that we will pass the boolean value when we complete the task.

Having a Kie Workbench project that has this process, build and deploy it. Now we can focus on the client app, because the process will be available for remote usage.

Using the Remote Java API

Our client application will use the Remote API to start process instances, get the value of process variables and access user tasks for PM and HR. We created a simple class to do some actions with the server. The full source code of this example is available at: https://github.com/jesuino/jbpm-rewards-client/blob/master/rewards-client/src/main/java/org/jugvale/rewardclient/RewardService.java

Here’s how our RuntimeEngine is created:

private RuntimeEngine engine;
private KieSession ksession;
private TaskService taskService;
private AuditService auditService;

private RewardService() throws MalformedURLException {
engine = RemoteRuntimeEngineFactory.newRestBuilder()
        .addDeploymentId(DEPLOYMENT_ID).addUserName(USERNAME)
        .addPassword(PASSWORD).addUrl(new URL(SERVER_URL)).build();
taskService = engine.getTaskService();
ksession = engine.getKieSession();
auditService = engine.getAuditService();
}

Now we can do a few actions with the server calling methods from ksession, taskService or auditService. Start a process passing a map as parameter:

public void startRewardProcess(String employeeName) {
    Map<String, Object> params = new HashMap<>();
    params.put(P_EMPLOYEE, employeeName);
    ksession.startProcess(PROCESS_ID, params);
}

Doing actions with tasks:

public void doTask(long taskId, boolean approve) {
    Map<String, Object> params =  new HashMap<>();
    params.put(T_APPROVAL_VAR, approve);
    taskService.claim(taskId, USERNAME);
    taskService.start(taskId, USERNAME);
    taskService.complete(taskId, USERNAME, params);
}

Clear the history of the running server (DANGEREOUS METHOD!):

public void clearHistory() {
    auditService.clear();
}

Retrieve a variable value using a process instance ID:

private String getVariableValue(long piid, String varName) {
    String value = null;
    List<? extends VariableInstanceLog> variables = auditService
            .findVariableInstances(piid, varName);
    if (variables.size() > 0)
        value = variables.get(0).getValue();
    return value;
}

There are, of course, a lot of other possibilities. These are just some possible remote operations to demonstrate the use of the Remote API.

AuthorWilliam Antônio Siqueira has about 6 years of Java programming experience. He started with JavaFX since its first release and since then he follows all the JavaFX updates. He regularly blogs about JavaFX, JBoss and Java application on fxapps.blogspot.com He also founded a JUG on his region which has about 100 members. Currently he works for Red Hat supporting and helping on JBoss products maintenance. His main areas of interest are Java EE, REST Web Services, jBPM and JavaFX.

Introduction to jBPM 6

This tutorial is an introduction to the jBPM 6 platform which has now reached its final release, bringing lots of power to your business processes. For those which are new to jBPM, you should be aware that jBPM is a Business Process Engine that allows defining executing an monitoring your business processes. jBPM is distributed as a set of libraries therefore you are free to choose whether to use it embedded in your applications or simply using it as a BPM Service, for example via the REST API.

In this tutorial we will learn at first how to install the jBPM 6 platform on your machine an create a simple demo process from the jbpm console. In the next lessons we will learn how to run more complex examples using User Tasks and Forms.

Installing jBPM 6

Requirements: You need Apache ant installed on your machine in order to be able to run the installer

Why do we need an installer ?

Technically, jBPM does not need any installer to use it: it is simply made up of a set of JAR files which can be added as a dependency to your project. The installer, however buys you some useful toolings such as: Kie WorkBench or the Eclipse tooling which can be used for Process and rules authoring and testing.

Start by downloading the full installer from: http://www.jbpm.org/download/download.html

Once downloaded, check the file build.properties which defines several things such as the Application Server version that will contain the KieWorkBench and the Database to be used:

jboss.server.wildfly.version=8.2.1.Final
jboss.server.version=wildfly-${jboss.server.wildfly.version}
jboss.home=./${jboss.server.version}
jboss.download.url=http://download.jboss.org/wildfly/${jboss.server.wildfly.version}/${jboss.server.version}.zip
jboss.server.conf.dir=${jboss.home}/standalone/configuration
jboss.server.deploy.dir=${jboss.home}/standalone/deployments
jboss.server.data.dir=${jboss.home}/standalone/data
jboss.clean.repository=true
jboss.war.type=${jboss.server.version}

As you can see from the top line, by default the application server WildFly 8.2.1 will be installed. Change the value of the jboss.server.wildfly.version to download a different version of the Application server.

Configuring jbpm6 Database

Jbpm requires a Database for storing Process information and State. out of the box, it is configured to use the embedded in-memory H2 Database. As this configuration is included only for demonstrative purposes, we will show how to install some other Database on it such as MySQL.

It is assumed that you have an installed MySql database: let’s create a database named “jbpm” and an user named as well “jbpm” with full grant privileges:

create database jbpm;
 
CREATE USER 'jbpm'@'localhost' IDENTIFIED BY 'jbpm';
GRANT ALL PRIVILEGES ON *.* TO 'jbpm'@'localhost' WITH GRANT OPTION;

Next configure your build.properties file so that you use the MySQL JDBC Driver settings. At first comment the H2 database setting, next configure MySQL db driver as follows (adapt to your JDBC Driver name):

#db.driver.jar=${install.home}/db/driver/${db.driver.jar.name}
#db.driver.module.dir=${jboss.home}/modules/${db.driver.module.prefix}/main/
# default is H2
#H2.version=1.3.170
#db.name=h2
#db.driver.jar.name=${db.name}.jar
#db.driver.download.url=http://repo1.maven.org/maven2/com/h2database/h2/${H2.version}/h2-${H2.version}.jar

db.name=mysql
db.driver.module.prefix=com/mysql
db.driver.jar.name=mysql-connector-java-5.1.18.jar
db.driver.download.url=https://repository.jboss.org/nexus/service/local/repositories/central/content/mysql/mysql-connector-java/5.1.18/mysql-connector-java-5.1.18.jar 

Great, we’re almost done. Now we will configure the application server to use the MySQL datasource instead of the default H2 db. Reach out the standalone-full-wildfly-8.2.1.Final.xml and configure the jBPM Datasource in both files to use MySQL JDBC Driver:

<datasources>
   <datasource jndi-name="java:jboss/datasources/jbpmDS" pool-name="MySQLDS" enabled="true" use-java-context="true">
      <connection-url>jdbc:mysql://localhost:3306/jbpm</connection-url>
      <driver>mysql</driver>
      <pool />
      <security>
         <user-name>jbpm</user-name>
         <password>jbpm</password>
      </security>
   </datasource>
   <drivers>
      <driver name="mysql" module="com.mysql">
         <xa-datasource-class>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</xa-datasource-class>
      </driver>
   </drivers>
</datasources>

Now last thing we need to adapt is the MySQL dialect that is used in the persistence settings. Open the file jbpm-installer\db\jbpm-persistence-JPA2.xml and comment H2 dialect and replace it with:

<!--  <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />-->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>

Great! we are done and we can try running the installation with:

ant install.demo

This will requires just a few minutes as nothing should be downloaded but just expanded from your distribution.

A tweak for WildFly users

There is a known issue that the ejc (eclipse java compiler) jar included in that version of Wildfly is NOT recognising Java8 correctly, and is therefore falling back to Java 1.5 (where auto-casting of Long to long isn’t supported). In order to force the application server to use Java8 simply pass this System Property to the application server (ex. in JAVA_OPTS) : -Ddrools.dialect.java.compiler=1.8

Database schema creation required ?

The Database schema is created automatically, once that the engine is started, from the Entity classes. As an alternative, prior to launching the application server, you can execute the DDL scripts which are contained in the db\ddl-scripts\mysql5 folder of your installer:

mysql < jbpm mysql5-jbpm-schema.sql -u jbpm -p
mysql < quartz_tables_mysql.sql -u jbpm -p


 

Starting jBPM 6 engine

Once completed, we will start the application server and check out the jbpm console. Since the jbpm6 console contains some resources bound to the jms adapter, we will need starting jboss using the full (or full-ha) profile:

standalone.bat -c standalone-full.xml

Once the application server is up and running, verify that the jbpm-console has been deployed by reaching out the default address: http://localhost:8080/jbpm-console
The default users and their roles are picked up from the users.properties and roles.properties contained in the configuration folder of the application server. Choose one such as krisv/krisv and enter them in the console.

 

The KIE Workbench is a rich web application which can be used for a variety of purposes such as authoring processes, starting and monitoring them and their tasks. The first thing we will do is selecting from the upper Menu Authoring -> Project Authoring


From there, you will be able to access the “New Item” Menu where we will choose the “Project” option. Enter a name for the new project in the following window:


Now you will be requested to enter the Group Specification version for our project: as you can see, projects stored in jbpm6 repository are stored as Maven resources and you have even some ready-to use Maven artifacts for creating jbpm6 projects.


Save your Project. We will now create a Business Process in this project. Select from the New Item menu the option “Business Process“. Enter a name for the process and check that it’s part of your project.


Now the BPMN 2.0 editor will start: click on the Object library icon (“<<“) to show the palette of items you can add to your process. In this very basic example, we will just add a Script item (under the Tasks menu) and an End item (“End events”). Connect each item by clicking on the item and selecting the Edge option which will connect a pair of items. So your first process should look like this:

Now let’s specify an action to execute on the Script node: just select it and pickup the icon “<<” which is located on the right border of your process. Enter a Java expression in the “Script” field, such a basic HelloWorld Message.


Now click on the “Save” icon, in the process toolbar:


Now return to the upper menu Authoring->Project Authoring. In the upper right side, you will find the Save – Build And Deploy options.

Choose to Save changes first, then click on Build and Deploy. A quick popup message will inform you that the pom.xml has been saved and your project deployed. Now we will execute our first project: select the Process Management->Process Definition option. There you will find the demoprocess that we have just created and click on the start icon.


A window containing an automatically generated form will appear. As we didn’t enter any variable definition in our form, just click on the right arrow to launch your process:


The Instance Details frame will populate including the details of your process that we have just started.


As a confirmation that your process correctly executed, move to the Application Server console and check out for the log message:


Great! you have just completed your first jBPM 6 process. Do you want to check how to install jBPM 6 with another Database such as PostgreSQL? check this: Configuring jBPM 6 to use a non-default Database