此内容没有您所选择的语言版本。
Designing a decision service using guided rules
Abstract
Preface
As a business analyst or business rules developer, you can define business rules using the guided rules designer in Business Central. These guided rules are compiled into Drools Rule Language (DRL) and form the core of the decision service for your project.
Prerequisites
- The space and project for the guided rules have been created in Business Central. Each asset is associated with a project assigned to a team. For details, see Getting started with decision services.
Chapter 1. Decision-authoring assets in Red Hat Decision Manager
Red Hat Decision Manager supports several assets that you can use to define business decisions for your decision service. Each decision-authoring asset has different advantages, and you might prefer to use one or a combination of multiple assets depending on your goals and needs.
The following table highlights the main decision-authoring assets supported in Red Hat Decision Manager projects to help you decide or confirm the best method for defining decisions in your decision service.
Asset | Highlights | Authoring tools | Documentation |
---|---|---|---|
Decision Model and Notation (DMN) models |
| Business Central or other DMN-compliant editor | |
Guided decision tables |
| Business Central | |
Spreadsheet decision tables |
| Spreadsheet editor | Designing a decision service using spreadsheet decision tables |
Guided rules |
| Business Central | |
Guided rule templates |
| Business Central | |
DRL rules |
| Business Central or integrated development environment (IDE) | |
Predictive Model Markup Language (PMML) models |
| PMML or XML editor |
Chapter 2. Guided rules
Guided rules are business rules that you create in a UI-based guided rules designer in Business Central that leads you through the rule-creation process. The guided rules designer provides fields and options for acceptable input based on the data objects for the rule being defined. The guided rules that you define are compiled into Drools Rule Language (DRL) rules as with all other rule assets.
All data objects related to a guided rule must be in the same project package as the guided rule. Assets in the same package are imported by default. After you create the necessary data objects and the guided rule, you can use the Data Objects tab of the guided rules designer to verify that all required data objects are listed or to import other existing data objects by adding a New item.
Chapter 3. Data objects
Data objects are the building blocks for the rule assets that you create. Data objects are custom data types implemented as Java objects in specified packages of your project. For example, you might create a Person
object with data fields Name
, Address
, and DateOfBirth
to specify personal details for loan application rules. These custom data types determine what data your assets and your decision services are based on.
3.1. Creating data objects
The following procedure is a generic overview of creating data objects. It is not specific to a particular business asset.
Procedure
- In Business Central, go to Menu → Design → Projects and click the project name.
- Click Add Asset → Data Object.
Enter a unique Data Object name and select the Package where you want the data object to be available for other rule assets. Data objects with the same name cannot exist in the same package. In the specified DRL file, you can import a data object from any package.
Importing data objects from other packagesYou can import an existing data object from another package directly into the asset designers like guided rules or guided decision table designers. Select the relevant rule asset within the project and in the asset designer, go to Data Objects → New item to select the object to be imported.
- To make your data object persistable, select the Persistable checkbox. Persistable data objects are able to be stored in a database according to the JPA specification. The default JPA is Hibernate.
- Click Ok.
In the data object designer, click add field to add a field to the object with the attributes Id, Label, and Type. Required attributes are marked with an asterisk (*).
- Id: Enter the unique ID of the field.
- Label: (Optional) Enter a label for the field.
- Type: Enter the data type of the field.
List: (Optional) Select this check box to enable the field to hold multiple items for the specified type.
Figure 3.1. Add data fields to a data object
Click Create to add the new field, or click Create and continue to add the new field and continue adding other fields.
NoteTo edit a field, select the field row and use the general properties on the right side of the screen.
Chapter 4. Creating guided rules
Guided rules enable you to define business rules in a structured format, based on the data objects associated with the rules. You can create and define guided rules individually for your project.
Procedure
- In Business Central, go to Menu → Design → Projects and click the project name.
- Click Add Asset → Guided Rule.
Enter an informative Guided Rule name and select the appropriate Package. The package that you specify must be the same package where the required data objects have been assigned or will be assigned.
You can also select Show declared DSL sentences if any domain specific language (DSL) assets have been defined in your project. These DSL assets will then become usable objects for conditions and actions that you define in the guided rules designer.
Click Ok to create the rule asset.
The new guided rule is now listed in the Guided Rules panel of the Project Explorer, or in the Guided Rules (with DSL) panel if you selected the Show declared DSL sentences option.
- Click the Data Objects tab and confirm that all data objects required for your rules are listed. If not, click New item to import data objects from other packages, or create data objects within your package.
After all data objects are in place, return to the Model tab of the guided rules designer and use the buttons on the right side of the window to add and define the WHEN (condition) and THEN (action) sections of the rule, based on the available data objects.
Figure 4.1. The guided rules designer
The WHEN part of the rule contains the conditions that must be met to execute an action. For example, if a bank requires loan applicants to have over 21 years of age, then the WHEN condition of an
Underage
rule would beAge | less than | 21
.The THEN part of the rule contains the actions to be performed when the conditional part of the rule has been met. For example, when the loan applicant is under 21 years old, the THEN action would set
approved
tofalse
, declining the loan because the applicant is under age.You can also specify exceptions for more complex rules, such as if a bank may approve of an under-aged applicant when a guarantor is involved. In that case, you would create or import a guarantor data object and then add the field to the guided rule.
- After you define all components of the rule, click Validate in the upper-right toolbar of the guided rules designer to validate the guided rule. If the rule validation fails, address any problems described in the error message, review all components in the rule, and try again to validate the rule until the rule passes.
- Click Save in the guided rules designer to save your work.
4.1. Adding WHEN conditions in guided rules
The WHEN part of the rule contains the conditions that must be met to execute an action. For example, if a bank requires loan applicants to have over 21 years of age, then the WHEN condition of an Underage
rule would be Age | less than | 21
. You can set simple or complex conditions to determine how and when your rules are applied.
Prerequisites
- All data objects required for your rules have been created or imported and are listed in the Data Objects tab of the guided rules designer.
Procedure
In the guided rules designer, click the plus icon ( ) on the right side of the
WHEN
section.The Add a condition to the rule window with the available condition elements opens.
Figure 4.2. Add a condition to the rule
The list includes the data objects from the Data Objects tab of the guided rules designer, any DSL objects defined for the package (if you selected Show declared DSL sentences when you created this guided rule), and the following standard options:
- The following does not exist: Use this to specify facts and constraints that must not exist.
- The following exists: Use this to specify facts and constraints that must exist. This option is triggered on only the first match, not subsequent matches.
- Any of the following are true: Use this to list any facts or constraints that must be true.
-
From: Use this to define a
From
conditional element for the rule. -
From Accumulate: Use this to define an
Accumulate
conditional element for the rule. -
From Collect: Use this to define a
Collect
conditional element for the rule. -
From Entry Point: Use this to define an
Entry Point
for the pattern. - Free form DRL: Use this to insert a free-form DRL field where you can define condition elements freely, without the guided rules designer.
- Choose a condition element (for example, LoanApplication) and click Ok.
Click the condition element in the guided rules designer and use the Modify constraints for LoanApplication window to add a restriction on a field, apply multiple field constraints, add a new formula style expression, apply an expression editor, or set a variable name.
Figure 4.3. Modify a condition
NoteA variable name enables you to identify a fact or field in other constructs within the guided rule. For example, you could set the variable of
LoanApplication
toa
and then referencea
in a separateBankruptcy
constraint that specifies which application the bankruptcy is based on.a : LoanApplication() Bankruptcy( application == a ).
After you select a constraint, the window closes automatically.
-
Choose an operator for the restriction (for example,
greater than
) from the drop-down menu next to the added restriction. - Click the edit icon ( ) to define the field value. The field value can be a literal value, a formula, or a full MVEL expression.
To apply multiple field constraints, click the condition and in the Modify constraints for LoanApplication window, select All of(And) or Any of(Or) from the Multiple field constraint drop-down menu.
Figure 4.4. Add multiple field constraints
- Click the constraint in the guided rules designer and further define the field value.
- After you define all condition components of the rule, click Validate in the upper-right toolbar of the guided rules designer to validate the guided rule conditions. If the rule validation fails, address any problems described in the error message, review all components in the rule, and try again to validate the rule until the rule passes.
- Click Save in the guided rules designer to save your work.
4.2. Adding THEN actions in guided rules
The THEN part of the rule contains the actions to be performed when the WHEN condition of the rule has been met. For example, when a loan applicant is under 21 years old, the THEN action might set approved
to false
, declining the loan because the applicant is under age. You can set simple or complex actions to determine how and when your rules are applied.
Prerequisites
- All data objects required for your rules have been created or imported and are listed in the Data Objects tab of the guided rules designer.
Procedure
In the guided rules designer, click the plus icon ( ) on the right side of the
THEN
section.The Add a new action window with the available action elements opens.
Figure 4.5. Add a new action to the rule
The list includes insertion and modification options based on the data objects in the Data Objects tab of the guided rules designer, and on any DSL objects defined for the package (if you selected Show declared DSL sentences when you created this guided rule):
-
Change field values of: Use this to set the value of fields on a fact (such as
LoanApplication
) without notifying the decision engine of the change. - Delete: Use this to delete a fact.
- Modify: Use this to specify fields to be modified for a fact and to notify the decision engine of the change.
- Insert fact: Use this to insert a fact and define resulting fields and values for the fact.
- Logically Insert fact: Use this to insert a fact logically into the decision engine and define resulting fields and values for the fact. The decision engine is responsible for logical decisions on insertions and retractions of facts. After regular or stated insertions, facts have to be retracted explicitly. After logical insertions, facts are automatically retracted when the conditions that originally asserted the facts are no longer true.
- Add free form DRL: Use this to insert a free-form DRL field where you can define condition elements freely, without the guided rules designer.
- Call method on: Use this to invoke a method from another fact.
-
Change field values of: Use this to set the value of fields on a fact (such as
- Choose an action element (for example, Modify) and click Ok.
Click the action element in the guided rules designer and use the Add a field window to select a field.
Figure 4.6. Add a field
After you select a field, the window closes automatically.
- Click the edit icon ( ) to define the field value. The field value can be a literal value or a formula.
- After you define all action components of the rule, click Validate in the upper-right toolbar of the guided rules designer to validate the guided rule actions. If the rule validation fails, address any problems described in the error message, review all components in the rule, and try again to validate the rule until the rule passes.
- Click Save in the guided rules designer to save your work.
4.3. Adding other rule options
You can also use the rule designer to add metadata within a rule, define additional rule attributes (such as salience
and no-loop
), and freeze areas of the rule to restrict modifications to conditions or actions.
Procedure
- In the rule designer, click (show options…) under the THEN section.
- Click the plus icon ( ) on the right side of the window to add options.
Select an option to be added to the rule:
- Metadata: Enter a metadata label and click the plus icon ( ). Then enter any needed data in the field provided in the rule designer.
- Attribute: Select from the list of rule attributes. Then further define the value in the field or option displayed in the rule designer.
Freeze areas for editing: Select Conditions or Actions to restrict the area from being modified in the rule designer.
Figure 4.7. Rule options
- Click Save in the rule designer to save your work.
4.3.1. Rule attributes
Rule attributes are additional specifications that you can add to business rules to modify rule behavior. The following table lists the names and supported values of the attributes that you can assign to rules:
Attribute | Value |
---|---|
| An integer defining the priority of the rule. Rules with a higher salience value are given higher priority when ordered in the activation queue.
Example: |
| A Boolean value. When the option is selected, the rule is enabled. When the option is not selected, the rule is disabled.
Example: |
|
A string containing a date and time definition. The rule can be activated only if the current date and time is after a
Example: |
|
A string containing a date and time definition. The rule cannot be activated if the current date and time is after the
Example: |
| A Boolean value. When the option is selected, the rule cannot be reactivated (looped) if a consequence of the rule re-triggers a previously met condition. When the condition is not selected, the rule can be looped in these circumstances.
Example: |
| A string identifying an agenda group to which you want to assign the rule. Agenda groups allow you to partition the agenda to provide more execution control over groups of rules. Only rules in an agenda group that has acquired a focus are able to be activated.
Example: |
| A string identifying an activation (or XOR) group to which you want to assign the rule. In activation groups, only one rule can be activated. The first rule to fire will cancel all pending activations of all rules in the activation group.
Example: |
| A long integer value defining the duration of time in milliseconds after which the rule can be activated, if the rule conditions are still met.
Example: |
|
A string identifying either
Example: |
| A Quartz calendar definition for scheduling the rule.
Example: |
| A Boolean value, applicable only to rules within agenda groups. When the option is selected, the next time the rule is activated, a focus is automatically given to the agenda group to which the rule is assigned.
Example: |
|
A Boolean value, applicable only to rules within rule flow groups or agenda groups. When the option is selected, the next time the ruleflow group for the rule becomes active or the agenda group for the rule receives a focus, the rule cannot be activated again until the ruleflow group is no longer active or the agenda group loses the focus. This is a stronger version of the
Example: |
| A string identifying a rule flow group. In rule flow groups, rules can fire only when the group is activated by the associated rule flow.
Example: |
|
A string identifying either
Example: |
Chapter 5. Executing rules
After you identify example rules or create your own rules in Business Central, you can build and deploy the associated project and execute rules locally or on Decision Server to test the rules.
Prerequisites
- Business Central and Decision Server are installed and running. For installation options, see Planning a Red Hat Decision Manager installation.
Procedure
- In Business Central, go to Menu → Design → Projects and click the project name.
In the upper-right corner of the project Assets page, click Deploy to build the project and deploy it to Decision Server. If the build fails, address any problems described in the Alerts panel at the bottom of the screen.
For more information about project deployment options, see Packaging and deploying a Red Hat Decision Manager project.
Create a Maven or Java project outside of Business Central, if not created already, that you can use for executing rules locally or that you can use as a client application for executing rules on Decision Server. The project must contain a
pom.xml
file and any other required components for executing the project resources.For example test projects, see "Other methods for creating and executing DRL rules".
Open the
pom.xml
file of your test project or client application and add the following dependencies, if not added already:-
kie-ci
: Enables your client application to load Business Central project data locally usingReleaseId
-
kie-server-client
: Enables your client application to interact remotely with assets on Decision Server -
slf4j
: (Optional) Enables your client application to use Simple Logging Facade for Java (SLF4J) to return debug logging information after you interact with Decision Server
Example dependencies for Red Hat Decision Manager 7.4 in a client application
pom.xml
file:<!-- For local execution --> <dependency> <groupId>org.kie</groupId> <artifactId>kie-ci</artifactId> <version>7.23.0.Final-redhat-00002</version> </dependency> <!-- For remote execution on Decision Server --> <dependency> <groupId>org.kie.server</groupId> <artifactId>kie-server-client</artifactId> <version>7.23.0.Final-redhat-00002</version> </dependency> <!-- For debug logging (optional) --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.25</version> </dependency>
For available versions of these artifacts, search the group ID and artifact ID in the Nexus Repository Manager online.
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.xml
file. 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:
<dependency> <groupId>com.redhat.ba</groupId> <artifactId>ba-platform-bom</artifactId> <version>7.4.0.GA-redhat-00002</version> <scope>import</scope> <type>pom</type> </dependency>
For more information about the Red Hat Business Automation BOM, see What is the mapping between Red Hat Decision Manager and the Maven library version?.
-
Ensure that the dependencies for artifacts containing model classes are defined in the client application
pom.xml
file exactly as they appear in thepom.xml
file of the deployed project. If dependencies for model classes differ between the client application and your projects, execution errors can occur.To access the project
pom.xml
file in Business Central, 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 → pom.xml.For example, the following
Person
class dependency appears in both the client and deployed projectpom.xml
files:<dependency> <groupId>com.sample</groupId> <artifactId>Person</artifactId> <version>1.0.0</version> </dependency>
If you added the
slf4j
dependency to the client applicationpom.xml
file for debug logging, create asimplelogger.properties
file on the relevant classpath (for example, insrc/main/resources/META-INF
in Maven) with the following content:org.slf4j.simpleLogger.defaultLogLevel=debug
In your client application, create a
.java
main class containing the necessary imports and amain()
method to load the KIE base, insert facts, and execute the rules.For example, a
Person
object in a project contains getter and setter methods to set and retrieve the first name, last name, hourly rate, and the wage of a person. The followingWage
rule in a project calculates the wage and hourly rate values and displays a message based on the result:package com.sample; import com.sample.Person; dialect "java" rule "Wage" when Person(hourlyRate * wage > 100) Person(name : firstName, surname : lastName) then System.out.println("Hello" + " " + name + " " + surname + "!"); System.out.println("You are rich!"); end
To test this rule locally outside of Decision Server (if desired), configure the
.java
class to import KIE services, a KIE container, and a KIE session, and then use themain()
method to fire all rules against a defined fact model:Executing rules locally
import org.kie.api.KieServices; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; public class RulesTest { public static final void main(String[] args) { try { // Identify the project in the local repository: ReleaseId rid = new ReleaseId(); rid.setGroupId("com.myspace"); rid.setArtifactId("MyProject"); rid.setVersion("1.0.0"); // Load the KIE base: KieServices ks = KieServices.Factory.get(); KieContainer kContainer = ks.newKieContainer(rid); KieSession kSession = kContainer.newKieSession(); // Set up the fact model: Person p = new Person(); p.setWage(12); p.setFirstName("Tom"); p.setLastName("Summers"); p.setHourlyRate(10); // Insert the person into the session: kSession.insert(p); // Fire all rules: kSession.fireAllRules(); kSession.dispose(); } catch (Throwable t) { t.printStackTrace(); } } }
To test this rule on Decision Server, configure the
.java
class with the imports and rule execution information similarly to the local example, and additionally specify KIE services configuration and KIE services client details:Executing rules on Decision Server
package com.sample; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.kie.api.command.BatchExecutionCommand; import org.kie.api.command.Command; import org.kie.api.KieServices; import org.kie.api.runtime.ExecutionResults; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import org.kie.server.api.marshalling.MarshallingFormat; import org.kie.server.api.model.ServiceResponse; import org.kie.server.client.KieServicesClient; import org.kie.server.client.KieServicesConfiguration; import org.kie.server.client.KieServicesFactory; import org.kie.server.client.RuleServicesClient; import com.sample.Person; public class RulesTest { private static final String containerName = "testProject"; private static final String sessionName = "myStatelessSession"; public static final void main(String[] args) { try { // Define KIE services configuration and client: Set<Class<?>> allClasses = new HashSet<Class<?>>(); allClasses.add(Person.class); String serverUrl = "http://$HOST:$PORT/kie-server/services/rest/server"; String username = "$USERNAME"; String password = "$PASSWORD"; KieServicesConfiguration config = KieServicesFactory.newRestConfiguration(serverUrl, username, password); config.setMarshallingFormat(MarshallingFormat.JAXB); config.addExtraClasses(allClasses); KieServicesClient kieServicesClient = KieServicesFactory.newKieServicesClient(config); // Set up the fact model: Person p = new Person(); p.setWage(12); p.setFirstName("Tom"); p.setLastName("Summers"); p.setHourlyRate(10); // Insert Person into the session: KieCommands kieCommands = KieServices.Factory.get().getCommands(); List<Command> commandList = new ArrayList<Command>(); commandList.add(kieCommands.newInsert(p, "personReturnId")); // Fire all rules: commandList.add(kieCommands.newFireAllRules("numberOfFiredRules")); BatchExecutionCommand batch = kieCommands.newBatchExecution(commandList, sessionName); // Use rule services client to send request: RuleServicesClient ruleClient = kieServicesClient.getServicesClient(RuleServicesClient.class); ServiceResponse<ExecutionResults> executeResponse = ruleClient.executeCommandsWithResults(containerName, batch); System.out.println("number of fired rules:" + executeResponse.getResult().getValue("numberOfFiredRules")); } catch (Throwable t) { t.printStackTrace(); } } }
Run the configured
.java
class from your project directory. You can run the file in your development platform (such as Red Hat JBoss Developer Studio) or in the command line.Example Maven execution (within project directory):
mvn clean install exec:java -Dexec.mainClass="com.sample.app.RulesTest"
Example Java execution (within project directory)
javac -classpath "./$DEPENDENCIES/*:." RulesTest.java java -classpath "./$DEPENDENCIES/*:." RulesTest
- Review the rule execution status in the command line and in the server log. If any rules do not execute as expected, review the configured rules in the project and the main class configuration to validate the data provided.
5.1. Executable rule models
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-plugin
to 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
mvel
expressions 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 12 bound variables only (including the built-in drools
variable). For example, the following rule consequence uses more than 12 bound variables and creates a compilation error:
... then $input.setNo13Count(functions.sumOf(new Object[]{$no1Count_1, $no2Count_1, $no3Count_1, ..., $no13Count_1}).intValue()); $input.getFirings().add("fired"); update($input);
5.1.1. Embedding an executable rule model in a Maven project
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.xml
file of your Maven project, ensure that the packaging type is set tokjar
and add thekie-maven-plugin
build component:<packaging>kjar</packaging> ... <build> <plugins> <plugin> <groupId>org.kie</groupId> <artifactId>kie-maven-plugin</artifactId> <version>${rhdm.version}</version> <extensions>true</extensions> </plugin> </plugins> </build>
The
kjar
packaging type activates thekie-maven-plugin
component 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.23.0.Final-redhat-00002). 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.xml
file. 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:
<dependency> <groupId>com.redhat.ba</groupId> <artifactId>ba-platform-bom</artifactId> <version>7.4.0.GA-redhat-00002</version> <scope>import</scope> <type>pom</type> </dependency>
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.xml
file 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
<dependency> <groupId>org.drools</groupId> <artifactId>drools-canonical-model</artifactId> <version>${rhdm.version}</version> </dependency> <dependency> <groupId>org.drools</groupId> <artifactId>drools-model-compiler</artifactId> <version>${rhdm.version}</version> </dependency>
-
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>
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
-
For more information about packaging Maven projects, see Packaging and deploying a Red Hat Decision Manager project.
5.1.2. Embedding an executable rule model in a Java application
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
<dependency> <groupId>org.drools</groupId> <artifactId>drools-canonical-model</artifactId> <version>${rhdm.version}</version> </dependency> <dependency> <groupId>org.drools</groupId> <artifactId>drools-model-compiler</artifactId> <version>${rhdm.version}</version> </dependency>
The
<version>
is the Maven artifact version for Red Hat Decision Manager currently used in your project (for example, 7.23.0.Final-redhat-00002).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.xml
file. 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:
<dependency> <groupId>com.redhat.ba</groupId> <artifactId>ba-platform-bom</artifactId> <version>7.4.0.GA-redhat-00002</version> <scope>import</scope> <type>pom</type> </dependency>
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
KieFileSystem
and useKieBuilder
withbuildAll( ExecutableModelProject.class )
specified to build the assets from an executable model:import org.kie.api.KieServices; import org.kie.api.builder.KieFileSystem; import org.kie.api.builder.KieBuilder; KieServices ks = KieServices.Factory.get(); KieFileSystem kfs = ks.newKieFileSystem() kfs.write("src/main/resources/KBase1/ruleSet1.drl", stringContainingAValidDRL) .write("src/main/resources/dtable.xls", kieServices.getResources().newInputStreamResource(dtableFileStream)); KieBuilder kieBuilder = ks.newKieBuilder( kfs ); // Build from an executable model kieBuilder.buildAll( ExecutableModelProject.class ) assertEquals(0, kieBuilder.getResults().getMessages(Message.Level.ERROR).size());
After
KieFileSystem
is built from the executable model, the resultingKieSession
uses constraints based on lambda expressions instead of less-efficientmvel
expressions. IfbuildAll()
contains no arguments, the project is built in the standard method without an executable model.As a more manual alternative to using
KieFileSystem
for creating executable models, you can define aModel
with a fluent API and create aKieBase
from it:Model model = new ModelImpl().addRule( rule ); KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
For more information about packaging projects programmatically within a Java application, see Packaging and deploying a Red Hat Decision Manager project.
Chapter 6. Next steps
Appendix A. Versioning information
Documentation last updated on Friday, May 22, 2020.