Chapter 6. Other methods for creating and executing DRL rules
As an alternative to creating and managing DRL rules within the Business Central interface, you can create DRL rule files externally as part of a Maven or Java project using Red Hat CodeReady Studio or another integrated development environment (IDE). These standalone projects can then be integrated as knowledge JAR (KJAR) dependencies in existing Red Hat Decision Manager projects in Business Central. The DRL files in your standalone project must contain at a minimum the required package specification, import lists, and rule definitions. Any other DRL components, such as global variables and functions, are optional. All data objects related to a DRL rule must be included with your standalone DRL project or deployment.
You can also use executable rule models in your Maven or Java projects to provide a Java-based representation of a rule set for execution at build time. The executable model is a more efficient alternative to the standard asset packaging in Red Hat Decision Manager and enables KIE containers and KIE bases to be created more quickly, especially when you have large lists of DRL (Drools Rule Language) files and other Red Hat Decision Manager assets.
6.1. Creating and executing DRL rules in Red Hat CodeReady Studio Copy linkLink copied to clipboard!
You can use Red Hat CodeReady Studio to create DRL files with rules and integrate the files with your Red Hat Decision Manager decision service. This method of creating DRL rules is helpful if you already use Red Hat CodeReady Studio for your decision service and want to continue with the same workflow. If you do not already use this method, then the Business Central interface of Red Hat Decision Manager is recommended for creating DRL files and other rule assets.
Prerequisites
- Red Hat CodeReady Studio has been installed from the Red Hat Customer Portal.
Procedure
-
In the Red Hat CodeReady Studio, click File
New Project. -
In the New Project window that opens, select Drools
Drools Project and click Next. - Click the second icon to Create a project and populate it with some example files to help you get started quickly. Click Next.
Enter a Project name and select the Maven radio button as the project building option. The GAV values are generated automatically. You can update these values as needed for your project:
-
Group ID:
com.sample -
Artifact ID:
my-project -
Version:
1.0.0-SNAPSHOT
-
Group ID:
Click Finish to create the project.
This configuration sets up a basic project structure, class path, and sample rules. The following is an overview of the project structure:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow Notice the following elements:
-
A
Sample.drlrule file in thesrc/main/resourcesdirectory, containing an exampleHello WorldandGoodByerules. -
A
DroolsTest.javafile under thesrc/main/javadirectory in thecom.samplepackage. TheDroolsTestclass can be used to execute theSample.drlrule. -
The
Drools Librarydirectory, which acts as a custom class path containing JAR files necessary for execution.
You can edit the existing
Sample.drlfile andDroolsTest.javafiles with new configurations as needed, or create new rule and object files. In this procedure, you are creating a new rule and new Java objects.-
A
Create a Java object on which the rule or rules will operate.
In this example, a
Person.javafile is created inmy-project/src/main/java/com.sample. ThePersonclass contains getter and setter methods to set and retrieve the first name, last name, hourly rate, and the wage of a person:Copy to Clipboard Copied! Toggle word wrap Toggle overflow -
Click File
Save to save the file. Create a rule file in
.drlformat inmy-project/src/main/resources/rules. The DRL file must contain at a minimum a package specification, an import list of data objects to be used by the rule or rules, and one or more rules withwhenconditions andthenactions.The following
Wage.drlfile contains aWagerule that imports thePersonclass, calculates the wage and hourly rate values, and displays a message based on the result:Copy to Clipboard Copied! Toggle word wrap Toggle overflow -
Click File
Save to save the file. Create a main class and save it to the same directory as the Java object that you created. The main class will load the KIE base and execute rules.
NoteYou can also add the
main()method andPersonclass within a single Java object file, similar to theDroolsTest.javasample file.In the main class, add the required
importstatements to import KIE services, a KIE container, and a KIE session. Then load the KIE base, insert facts, and execute the rule from themain()method that passes the fact model to the rule.In this example, a
RulesTest.javafile is created inmy-project/src/main/java/com.samplewith the required imports andmain()method:Copy to Clipboard Copied! Toggle word wrap Toggle overflow -
Click File
Save to save the file. -
After you create and save all DRL assets in your project, right-click your project folder and select Run As
Java Application to build the project. If the project build fails, address any problems described in the Problems tab of the lower window in CodeReady Studio, and try again to validate the project until the project builds.
If Java Application is not an option when you right-click your project and select Run As, then go to Run As
To integrate the new rule assets with an existing project in Red Hat Decision Manager, you can compile the new project as a knowledge JAR (KJAR) and add it as a dependency in the pom.xml file of the project in Business Central. To access the project pom.xml file in Business Central, you can select any existing asset in the project and then in the Project Explorer menu on the left side of the screen, click the Customize View gear icon and select Repository View
6.2. Creating and executing DRL rules using Java Copy linkLink copied to clipboard!
You can use Java objects to create DRL files with rules and integrate the objects with your Red Hat Decision Manager decision service. This method of creating DRL rules is helpful if you already use external Java objects for your decision service and want to continue with the same workflow. If you do not already use this method, then the Business Central interface of Red Hat Decision Manager is recommended for creating DRL files and other rule assets.
Procedure
Create a Java object on which the rule or rules will operate.
In this example, a
Person.javafile is created in a directorymy-project. ThePersonclass contains getter and setter methods to set and retrieve the first name, last name, hourly rate, and the wage of a person:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Create a rule file in
.drlformat under themy-projectdirectory. The DRL file must contain at a minimum a package specification (if applicable), an import list of data objects to be used by the rule or rules, and one or more rules withwhenconditions andthenactions.The following
Wage.drlfile contains aWagerule that calculates the wage and hourly rate values and displays a message based on the result:Copy to Clipboard Copied! Toggle word wrap Toggle overflow - Create a main class and save it to the same directory as the Java object that you created. The main class will load the KIE base and execute rules.
In the main class, add the required
importstatements to import KIE services, a KIE container, and a KIE session. Then load the KIE base, insert facts, and execute the rule from themain()method that passes the fact model to the rule.In this example, a
RulesTest.javafile is created inmy-projectwith the required imports andmain()method:Copy to Clipboard Copied! Toggle word wrap Toggle overflow -
Download the Red Hat Decision Manager 7.5.1 Source Distribution ZIP file from the Red Hat Customer Portal and extract it under
my-project/dm-engine-jars/. In the
my-project/META-INFdirectory, create akmodule.xmlmetadata file with the following content:<?xml version="1.0" encoding="UTF-8"?> <kmodule xmlns="http://www.drools.org/xsd/kmodule"> </kmodule>
<?xml version="1.0" encoding="UTF-8"?> <kmodule xmlns="http://www.drools.org/xsd/kmodule"> </kmodule>Copy to Clipboard Copied! Toggle word wrap Toggle overflow This
kmodule.xmlfile is a KIE module descriptor that selects resources to KIE bases and configures sessions. This file enables you to define and configure one or more KIE bases, and to include DRL files from specificpackagesin a specific KIE base. You can also create one or more KIE sessions from each KIE base.The following example shows a more advanced
kmodule.xmlfile:Copy to Clipboard Copied! Toggle word wrap Toggle overflow This example defines two KIE bases. Two KIE sessions are instantiated from the
KBase1KIE base, and one KIE session fromKBase2. The KIE session fromKBase2is astatelessKIE session, which means that data from a previous invocation of the KIE session (the previous session state) is discarded between session invocations. Specificpackagesof rule assets are included with both KIE bases. When you specify packages in this way, you must organize your DRL files in a folder structure that reflects the specified packages.After you create and save all DRL assets in your Java object, navigate to the
my-projectdirectory in the command line and run the following command to build your Java files. ReplaceRulesTest.javawith the name of your Java main class.javac -classpath "./dm-engine-jars/*:." RulesTest.java
javac -classpath "./dm-engine-jars/*:." RulesTest.javaCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the build fails, address any problems described in the command line error messages and try again to validate the Java object until the object passes.
After your Java files build successfully, run the following command to execute the rules locally. Replace
RulesTestwith the prefix of your Java main class.java -classpath "./dm-engine-jars/*:." RulesTest
java -classpath "./dm-engine-jars/*:." RulesTestCopy to Clipboard Copied! Toggle word wrap Toggle overflow - Review the rules to ensure that they executed properly, and address any needed changes in the Java files.
To integrate the new rule assets with an existing project in Red Hat Decision Manager, you can compile the new Java project as a knowledge JAR (KJAR) and add it as a dependency in the pom.xml file of the project in Business Central. To access the project pom.xml file in Business Central, you can select any existing asset in the project and then in the Project Explorer menu on the left side of the screen, click the Customize View gear icon and select Repository View
6.3. Creating and executing DRL rules using Maven Copy linkLink copied to clipboard!
You can use Maven archetypes to create DRL files with rules and integrate the archetypes with your Red Hat Decision Manager decision service. This method of creating DRL rules is helpful if you already use external Maven archetypes for your decision service and want to continue with the same workflow. If you do not already use this method, then the Business Central interface of Red Hat Decision Manager is recommended for creating DRL files and other rule assets.
Procedure
Navigate to a directory where you want to create a Maven archetype and run the following command:
mvn archetype:generate -DgroupId=com.sample.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
mvn archetype:generate -DgroupId=com.sample.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=falseCopy to Clipboard Copied! Toggle word wrap Toggle overflow This creates a directory
my-appwith the following structure:Copy to Clipboard Copied! Toggle word wrap Toggle overflow The
my-appdirectory contains the following key components:-
A
src/maindirectory for storing the application sources -
A
src/testdirectory for storing the test sources -
A
pom.xmlfile with the project configuration
-
A
Create a Java object on which the rule or rules will operate within the Maven archetype.
In this example, a
Person.javafile is created in the directorymy-app/src/main/java/com/sample/app. ThePersonclass contains getter and setter methods to set and retrieve the first name, last name, hourly rate, and the wage of a person:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Create a rule file in
.drlformat inmy-app/src/main/resources/rules. The DRL file must contain at a minimum a package specification, an import list of data objects to be used by the rule or rules, and one or more rules withwhenconditions andthenactions.The following
Wage.drlfile contains aWagerule that imports thePersonclass, calculates the wage and hourly rate values, and displays a message based on the result:Copy to Clipboard Copied! Toggle word wrap Toggle overflow In the
my-app/src/main/resources/META-INFdirectory, create akmodule.xmlmetadata file with the following content:<?xml version="1.0" encoding="UTF-8"?> <kmodule xmlns="http://www.drools.org/xsd/kmodule"> </kmodule>
<?xml version="1.0" encoding="UTF-8"?> <kmodule xmlns="http://www.drools.org/xsd/kmodule"> </kmodule>Copy to Clipboard Copied! Toggle word wrap Toggle overflow This
kmodule.xmlfile is a KIE module descriptor that selects resources to KIE bases and configures sessions. This file enables you to define and configure one or more KIE bases, and to include DRL files from specificpackagesin a specific KIE base. You can also create one or more KIE sessions from each KIE base.The following example shows a more advanced
kmodule.xmlfile:Copy to Clipboard Copied! Toggle word wrap Toggle overflow This example defines two KIE bases. Two KIE sessions are instantiated from the
KBase1KIE base, and one KIE session fromKBase2. The KIE session fromKBase2is astatelessKIE session, which means that data from a previous invocation of the KIE session (the previous session state) is discarded between session invocations. Specificpackagesof rule assets are included with both KIE bases. When you specify packages in this way, you must organize your DRL files in a folder structure that reflects the specified packages.In the
my-app/pom.xmlconfiguration file, specify the libraries that your application requires. Provide the Red Hat Decision Manager dependencies as well as thegroup ID,artifact ID, andversion(GAV) of your application.Copy to Clipboard Copied! Toggle word wrap Toggle overflow For information about Maven dependencies and the BOM (Bill of Materials) in Red Hat Decision Manager, see What is the mapping between Red Hat Decision Manager and Maven library version?.
-
Use the
testAppmethod inmy-app/src/test/java/com/sample/app/AppTest.javato test the rule. TheAppTest.javafile is created by Maven by default. In the
AppTest.javafile, add the requiredimportstatements to import KIE services, a KIE container, and a KIE session. Then load the KIE base, insert facts, and execute the rule from thetestApp()method that passes the fact model to the rule.Copy to Clipboard Copied! Toggle word wrap Toggle overflow After you create and save all DRL assets in your Maven archetype, navigate to the
my-appdirectory in the command line and run the following command to build your files:mvn clean install
mvn clean installCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the build fails, address any problems described in the command line error messages and try again to validate the files until the build is successful.
After your files build successfully, run the following command to execute the rules locally. Replace
com.sample.appwith your package name.mvn exec:java -Dexec.mainClass="com.sample.app"
mvn exec:java -Dexec.mainClass="com.sample.app"Copy to Clipboard Copied! Toggle word wrap Toggle overflow - Review the rules to ensure that they executed properly, and address any needed changes in the files.
To integrate the new rule assets with an existing project in Red Hat Decision Manager, you can compile the new Maven project as a knowledge JAR (KJAR) and add it as a dependency in the pom.xml file of the project in Business Central. To access the project pom.xml file in Business Central, you can select any existing asset in the project and then in the Project Explorer menu on the left side of the screen, click the Customize View gear icon and select Repository View
6.4. Executable rule models Copy linkLink copied to clipboard!
Executable rule models are embeddable models that provide a Java-based representation of a rule set for execution at build time. The executable model is a more efficient alternative to the standard asset packaging in Red Hat Decision Manager and enables KIE containers and KIE bases to be created more quickly, especially when you have large lists of DRL (Drools Rule Language) files and other Red Hat Decision Manager assets. The model is low level and enables you to provide all necessary execution information, such as the lambda expressions for the index evaluation.
Executable rule models provide the following specific advantages for your projects:
-
Compile time: Traditionally, a packaged Red Hat Decision Manager project (KJAR) contains a list of DRL files and other Red Hat Decision Manager artifacts that define the rule base together with some pre-generated classes implementing the constraints and the consequences. Those DRL files must be parsed and compiled when the KJAR is downloaded from the Maven repository and installed in a KIE container. This process can be slow, especially for large rule sets. With an executable model, you can package within the project KJAR the Java classes that implement the executable model of the project rule base and re-create the KIE container and its KIE bases out of it in a much faster way. In Maven projects, you use the
kie-maven-pluginto automatically generate the executable model sources from the DRL files during the compilation process. -
Run time: In an executable model, all constraints are defined as Java lambda expressions. The same lambda expressions are also used for constraints evaluation, so you no longer need to use
mvelexpressions for interpreted evaluation nor the just-in-time (JIT) process to transform themvel-based constraints into bytecode. This creates a quicker and more efficient run time. - Development time: An executable model enables you to develop and experiment with new features of the decision engine without needing to encode elements directly in the DRL format or modify the DRL parser to support them.
For query definitions in executable rule models, you can use up to 10 arguments only.
For variables within rule consequences in executable rule models, you can use up to 13 bound variables only (including the built-in drools variable). For example, the following rule consequence uses more than 13 bound variables and creates a compilation error:
...
then
$input.setNo14Count(functions.sumOf(new Object[]{$no1Count_1, $no2Count_1, $no3Count_1, ..., $no14Count_1}).intValue());
$input.getFirings().add("fired");
update($input);
...
then
$input.setNo14Count(functions.sumOf(new Object[]{$no1Count_1, $no2Count_1, $no3Count_1, ..., $no14Count_1}).intValue());
$input.getFirings().add("fired");
update($input);
6.4.1. Embedding an executable rule model in a Maven project Copy linkLink copied to clipboard!
You can embed an executable rule model in your Maven project to compile your rule assets more efficiently at build time.
Prerequisites
- You have a Mavenized project that contains Red Hat Decision Manager business assets.
Procedure
In the
pom.xmlfile of your Maven project, ensure that the packaging type is set tokjarand add thekie-maven-pluginbuild component:Copy to Clipboard Copied! Toggle word wrap Toggle overflow The
kjarpackaging type activates thekie-maven-plugincomponent to validate and pre-compile artifact resources. The<version>is the Maven artifact version for Red Hat Decision Manager currently used in your project (for example, 7.26.0.Final-redhat-00005). These settings are required to properly package the Maven project.NoteInstead of specifying a Red Hat Decision Manager
<version>for individual dependencies, consider adding the Red Hat Business Automation bill of materials (BOM) dependency to your projectpom.xmlfile. The Red Hat Business Automation BOM applies to both Red Hat Decision Manager and Red Hat Process Automation Manager. When you add the BOM files, the correct versions of transitive dependencies from the provided Maven repositories are included in the project.Example BOM dependency:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow For more information about the Red Hat Business Automation BOM, see What is the mapping between RHDM product and maven library version?.
Add the following dependencies to the
pom.xmlfile to enable rule assets to be built from an executable model:-
drools-canonical-model: Enables an executable canonical representation of a rule set model that is independent from Red Hat Decision Manager -
drools-model-compiler: Compiles the executable model into Red Hat Decision Manager internal data structures so that it can be executed by the decision engine
Copy to Clipboard Copied! Toggle word wrap Toggle overflow -
In a command terminal, navigate to your Maven project directory and run the following command to build the project from an executable model:
mvn clean install -DgenerateModel=<VALUE>
mvn clean install -DgenerateModel=<VALUE>Copy to Clipboard Copied! Toggle word wrap Toggle overflow The
-DgenerateModel=<VALUE>property enables the project to be built as a model-based KJAR instead of a DRL-based KJAR.Replace
<VALUE>with one of three values:-
YES: Generates the executable model corresponding to the DRL files in the original project and excludes the DRL files from the generated KJAR. -
WITHDRL: Generates the executable model corresponding to the DRL files in the original project and also adds the DRL files to the generated KJAR for documentation purposes (the KIE base is built from the executable model regardless). -
NO: Does not generate the executable model.
Example build command:
mvn clean install -DgenerateModel=YES
mvn clean install -DgenerateModel=YESCopy to Clipboard Copied! Toggle word wrap Toggle overflow -
For more information about packaging Maven projects, see Packaging and deploying a Red Hat Decision Manager project.
6.4.2. Embedding an executable rule model in a Java application Copy linkLink copied to clipboard!
You can embed an executable rule model programmatically within your Java application to compile your rule assets more efficiently at build time.
Prerequisites
- You have a Java application that contains Red Hat Decision Manager business assets.
Procedure
Add the following dependencies to the relevant classpath for your Java project:
-
drools-canonical-model: Enables an executable canonical representation of a rule set model that is independent from Red Hat Decision Manager -
drools-model-compiler: Compiles the executable model into Red Hat Decision Manager internal data structures so that it can be executed by the decision engine
Copy to Clipboard Copied! Toggle word wrap Toggle overflow The
<version>is the Maven artifact version for Red Hat Decision Manager currently used in your project (for example, 7.26.0.Final-redhat-00005).NoteInstead of specifying a Red Hat Decision Manager
<version>for individual dependencies, consider adding the Red Hat Business Automation bill of materials (BOM) dependency to your projectpom.xmlfile. The Red Hat Business Automation BOM applies to both Red Hat Decision Manager and Red Hat Process Automation Manager. When you add the BOM files, the correct versions of transitive dependencies from the provided Maven repositories are included in the project.Example BOM dependency:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow For more information about the Red Hat Business Automation BOM, see What is the mapping between RHDM product and maven library version?.
-
Add rule assets to the KIE virtual file system
KieFileSystemand useKieBuilderwithbuildAll( ExecutableModelProject.class )specified to build the assets from an executable model:Copy to Clipboard Copied! Toggle word wrap Toggle overflow After
KieFileSystemis built from the executable model, the resultingKieSessionuses constraints based on lambda expressions instead of less-efficientmvelexpressions. IfbuildAll()contains no arguments, the project is built in the standard method without an executable model.As a more manual alternative to using
KieFileSystemfor creating executable models, you can define aModelwith a fluent API and create aKieBasefrom it:Model model = new ModelImpl().addRule( rule ); KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
Model model = new ModelImpl().addRule( rule ); KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );Copy to Clipboard Copied! Toggle word wrap Toggle overflow
For more information about packaging projects programmatically within a Java application, see Packaging and deploying a Red Hat Decision Manager project.