[Tutorial updated on January 2019] In the following tutorial we will learn how to create a basic Hello World Drools project using Maven as project builder.

The prerequisite to this tutorial is that you have installed Maven on your pc. We will learn at first how to create a project from the shell. As an alternative, you can use an IDE like Eclipse with jBPM plugin or JBoss Developer Studio.

Create a new Maven Project

In order to get started you just need a basic Maven archetype which can be used to set up an initial structure for our projects. The maven-archetype-quickstart can be used for this purpose. From a shell, issue the following command:

mvn archetype:generate -DgroupId=com.sample.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Next step, we need to create the resources/META-INF to store our configuration file and resources/rules folder structure to hold our Rules scripts:

$ mkdir -p resources/META-INF
$ mkdir -p resources/rules

Add Drools dependencies

Once done with the archetype, let's work on the pom.xml file which contains our Maven project model. There, we are going to set the Drools dependencies:

<properties>
      <runtime.version>7.15.0.Final</runtime.version>
</properties>
<dependencies>
      <dependency>
         <groupId>org.kie</groupId>
         <artifactId>kie-api</artifactId>
         <version>${runtime.version}</version>
      </dependency>
      <dependency>
         <groupId>org.drools</groupId>
         <artifactId>drools-core</artifactId>
         <version>${runtime.version}</version>
      </dependency>
      <dependency>
         <groupId>org.drools</groupId>
         <artifactId>drools-compiler</artifactId>
         <version>${runtime.version}</version>
      </dependency>
      <dependency>
         <groupId>org.kie</groupId>
         <artifactId>kie-ci</artifactId>
         <version>${runtime.version}</version>
      </dependency>
</dependencies>

Add Classes and Rules

Ok, now we need to set up a simple Rule which is based on the Account class. This rule will issue a warning if the Account class' balance will drop below a certain value.

package com.sample.model;

public class Account {
    private Integer balance;


    public Account() {}
    public Integer getBalance() {
        return balance;
    }
    public void setBalance(Integer balance) {
        this.balance = balance;
    }
    public Account(Integer balance) {
        super();
        this.balance = balance;
    }
    public void withdraw(int money) {
        balance -= money;
    }
}

And here's our simple Rule:

package demo
import com.sample.model.Account
rule "accountBalanceAtLeast"
  when
  $account : Account( balance < 100 )
  then
  System.out.println("Warning! money running out!");
end
						

And now, let's code a simple Main class which will instantiate our process:

package com.sample;

import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

import com.sample.model.Account;

/**
 * This is a sample class to launch a rule.
 */
public class DroolsTest {

    public static final void main(String[] args) {
        try {
            // load up the knowledge base
	        KieServices ks = KieServices.Factory.get();
    	    KieContainer kContainer = ks.getKieClasspathContainer();
        	KieSession kSession = kContainer.newKieSession("ksession-rules");

            // go !
            Account account = new Account(200);
            account.withdraw(150);
            kSession.insert(account);
            kSession.fireAllRules();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

The Kie Session is declared in the file META-INF/kmodule.xml:

<kmodule xmlns="http://www.drools.org/xsd/kmodule">
    <kbase name="rules" packages="rules">
        <ksession name="ksession-rules"/>
    </kbase>
    <kbase name="dtables" packages="dtables">
        <ksession name="ksession-dtables"/>
    </kbase>
    <kbase name="process" packages="process">
        <ksession name="ksession-process"/>
    </kbase>
</kmodule>

Now last thing in order to run our main class is a maven compiler plugin and the maven exec plugin which is configured to run as main class com.sample.DroolsTest:

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
           <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.4.0</version>
            <configuration>
              <mainClass>com.sample.DroolsTest</mainClass>
            </configuration>
          </plugin>           
        </plugins>
</build>

You can compile and test your example using:

mvn clean package exec:java

The expected output is:

Warning! money running out!=============================Today is  Mon Apr 22 17:30:47 CEST 2013
[INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------[INFO] Total time: 4.649s
[INFO] Finished at: Mon Apr 22 17:30:47 CEST 2013
[INFO] Final Memory: 15M/109M
[INFO] ------------------------------------------------------------------------

You can find the source code for this Hello World example at: https://github.com/fmarchioni/mastertheboss/tree/master/DroolsMaven/CDI

Running the Hello World Drools with CDI

It is noteworthy to mention that CDI is now tightly integrated into the KIE API. It can be used to inject versioned KieSession and KieBases. Here is how to rewrite the above example using CDI:

package com.sample;

import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
import org.kie.api.cdi.KSession;
import org.kie.api.runtime.KieSession;

import com.sample.model.Account;

import javax.inject.Inject;
import java.io.PrintStream;

public class CDIExample {

    @Inject
    @KSession("ksession-rules")
    KieSession kSession;

    public void go(PrintStream out) {
     	Account account = new Account(200);
        account.withdraw(150);
        kSession.insert(account);
        kSession.fireAllRules();
    }

    public static void main(String[] args) {
        Weld w = new Weld();

        WeldContainer wc = w.initialize();
        CDIExample bean = wc.instance().select(CDIExample.class).get();
        bean.go(System.out);

        w.shutdown();
    }

}

In terms of dependencies you have to include the following dependencies in your project:

<dependencies>
    <dependency>
      <groupId>org.drools</groupId>
      <artifactId>drools-compiler</artifactId>
    </dependency>
    <dependency>
      <groupId>org.drools</groupId>
      <artifactId>drools-cdi</artifactId>
    </dependency>
    <dependency>
      <groupId>javax.enterprise</groupId>
      <artifactId>cdi-api</artifactId>
      <exclusions>
        <exclusion>
          <groupId>javax.el</groupId>
          <artifactId>javax.el-api</artifactId>
        </exclusion>
        <exclusion>
          <groupId>javax.interceptor</groupId>
          <artifactId>javax.interceptor-api</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.jboss.weld.se</groupId>
      <artifactId>weld-se-core</artifactId>
    </dependency>
    <dependency>
      <groupId>org.kie</groupId>
      <artifactId>kie-api</artifactId>
    </dependency>
</dependencies>

This project is available on github at https://github.com/fmarchioni/mastertheboss/tree/master/DroolsMaven/CDI

Using kie-drools-archetype

This tutorials shows how to create a Drools project using the basic Maven quickstart archetype. It is now available also a specific archetype named "kie-drools-archetype" which further simplifies the creation of Drools Projects.

If you are in a hurry, here's a quick Screen Cast of it:

To learn more: Creating a Drools Project using kie-drools-archetype

Continue Learning Drools through the following tutorials:

1) Coding Rules in Decision Tables

In Drools, Decision Tables are a way to generate rules from the data entered into a spreadsheet. The spreadsheet can be a standard Excel (XLS) or a CSV File.

Drools decision tables example

If you want to learn how to code your Rules into an excel Spread Sheet, keep reading this tutorial: Getting started with Decision Tables in Drools

2) Getting started with the Kie Execution Server

The Kie Server is a Java web application that allow us to expose rules and business process to be executed remotely using REST and JMS interfaces. The following tutorial shows how to install it on the top of WildFly: Configure Kie Execution Server on WildFly

3) Deploy your assets on the Business Central

Once that you are familiar with the Kie Execution Server, you can learn how install also the Business Central where you can design, build and deploy your assets. Here is the tutorial for you: Getting started with Business Central Workbench

0
0
0
s2smodern