Search

Designing a decision service using guided decision tables

download PDF
Red Hat Decision Manager 7.6

Red Hat Customer Content Services

Abstract

This document describes how to design a decision service using guided decision tables in Red Hat Decision Manager 7.6.

Preface

As a business analyst or business rules developer, you can use guided decision tables to define business rules in a wizard-led tabular format. These rules are compiled into Drools Rule Language (DRL) and form the core of the decision service for your project.

Note

You can also design your decision service using Decision Model and Notation (DMN) models instead of rule-based or table-based assets. For information about DMN support in Red Hat Decision Manager 7.6, see the following resources:

Prerequisites

  • The space and project for the guided decision tables have been created in Business Central. Each asset is associated with a project assigned to a space. 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.

Table 1.1. Decision-authoring assets supported in Red Hat Decision Manager
AssetHighlightsAuthoring toolsDocumentation

Decision Model and Notation (DMN) models

  • Are decision models based on a notation standard defined by the Object Management Group (OMG)
  • Use graphical decision requirements diagrams (DRDs) with one or more decision requirements graphs (DRGs) to trace business decision flows
  • Use an XML schema that allows the DMN models to be shared between DMN-compliant platforms
  • Support Friendly Enough Expression Language (FEEL) to define decision logic in DMN decision tables and other DMN boxed expressions
  • Are optimal for creating comprehensive, illustrative, and stable decision flows

Business Central or other DMN-compliant editor

Designing a decision service using DMN models

Guided decision tables

  • Are tables of rules that you create in a UI-based table designer in Business Central
  • Are a wizard-led alternative to spreadsheet decision tables
  • Provide fields and options for acceptable input
  • Support template keys and values for creating rule templates
  • Support hit policies, real-time validation, and other additional features not supported in other assets
  • Are optimal for creating rules in a controlled tabular format to minimize compilation errors

Business Central

Designing a decision service using guided decision tables

Spreadsheet decision tables

  • Are XLS or XLSX spreadsheet decision tables that you can upload into Business Central
  • Support template keys and values for creating rule templates
  • Are optimal for creating rules in decision tables already managed outside of Business Central
  • Have strict syntax requirements for rules to be compiled properly when uploaded

Spreadsheet editor

Designing a decision service using spreadsheet decision tables

Guided rules

  • Are individual rules that you create in a UI-based rule designer in Business Central
  • Provide fields and options for acceptable input
  • Are optimal for creating single rules in a controlled format to minimize compilation errors

Business Central

Designing a decision service using guided rules

Guided rule templates

  • Are reusable rule structures that you create in a UI-based template designer in Business Central
  • Provide fields and options for acceptable input
  • Support template keys and values for creating rule templates (fundamental to the purpose of this asset)
  • Are optimal for creating many rules with the same rule structure but with different defined field values

Business Central

Designing a decision service using guided rule templates

DRL rules

  • Are individual rules that you define directly in .drl text files
  • Provide the most flexibility for defining rules and other technicalities of rule behavior
  • Can be created in certain standalone environments and integrated with Red Hat Decision Manager
  • Are optimal for creating rules that require advanced DRL options
  • Have strict syntax requirements for rules to be compiled properly

Business Central or integrated development environment (IDE)

Designing a decision service using DRL rules

Predictive Model Markup Language (PMML) models

  • Are predictive data-analytic models based on a notation standard defined by the Data Mining Group (DMG)
  • Use an XML schema that allows the PMML models to be shared between PMML-compliant platforms
  • Support Regression, Scorecard, Tree, Mining, and other model types
  • Can be included with a standalone Red Hat Decision Manager project or imported into a project in Business Central
  • Are optimal for incorporating predictive data into decision services in Red Hat Decision Manager

PMML or XML editor

Designing a decision service using PMML models

Chapter 2. Guided decision tables

Guided decision tables are a wizard-led alternative to spreadsheet decision tables for defining business rules in a tabular format. With guided decision tables, you are led by a UI-based wizard in Business Central that helps you define rule attributes, metadata, conditions, and actions based on specified data objects in your project. After you create your guided decision tables, the rules you defined are compiled into Drools Rule Language (DRL) rules as with all other rule assets.

All data objects related to a guided decision table must be in the same project package as the guided decision table. Assets in the same package are imported by default. After you create the necessary data objects and the guided decision table, you can use the Data Objects tab of the guided decision tables 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

  1. In Business Central, go to MenuDesignProjects and click the project name.
  2. Click Add AssetData Object.
  3. 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 packages

    You 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.

  4. 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.
  5. Click Ok.
  6. 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

      Add data fields to a data object
  7. Click Create to add the new field, or click Create and continue to add the new field and continue adding other fields.

    Note

    To edit a field, select the field row and use the general properties on the right side of the screen.

Chapter 4. Creating guided decision tables

You can use guided decision tables to define rule attributes, metadata, conditions, and actions in a tabular format that can be added to your business rules project.

Procedure

  1. In Business Central, go to MenuDesignProjects and click the project name.
  2. Click Add AssetGuided Decision Table.
  3. Enter an informative Guided Decision Table 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.
  4. Select Use Wizard to finish setting up the table in the wizard, or leave this option unselected to finish creating the table and specify remaining configurations in the guided decision tables designer.
  5. Select the hit policy that you want your rows of rules in the table to conform to. For details, see Chapter 5, Hit policies for guided decision tables.
  6. Specify whether you want the Extended entry or Limited entry table. For details, see Section 5.1.1, “Types of guided decision tables”.
  7. Click Ok to complete the setup. If you have selected Use Wizard, the Guided Decision Table wizard is displayed. If you did not select the Use Wizard option, this prompt does not appear and you are taken directly to the table designer.

    For example, the following wizard setup is for a guided decision table in a loan application decision service:

    Figure 4.1. Create guided decision table

    6326 1
  8. If you are using the wizard, add any available imports, fact patterns, constraints, and actions, and select whether table columns should expand. Click Finish to close the wizard and view the table designer.

    Figure 4.2. Guided Decision Table wizard

    6328 1

In the guided decision tables designer, you can add or edit columns and rows, and make other final adjustments.

Chapter 5. Hit policies for guided decision tables

Hit policies determine the order in which rules (rows) in a guided decision table are applied, whether top to bottom, per specified priority, or other options.

The following hit policies are available:

  • None: (Default hit policy) Multiple rows can be executed and the verification warns about rows that conflict. Any decision tables that have been uploaded (using a non-guided decision table spreadsheet) will adopt this hit policy.
  • Resolved Hit: Only one row at a time can be executed according to specified priority, regardless of list order (you can give row 10 priority over row 5, for example). This means you can keep the order of the rows you want for visual readability, but specify priority exceptions.
  • Unique Hit: Only one row at a time can be executed, and each row must be unique, with no overlap of conditions being met. If more than one row is executed, then the verification produces a warning at development time.
  • First Hit: Only one row at a time can be executed in the order listed in the table, top to bottom.
  • Rule Order: Multiple rows can be executed and verification does not report conflicts between the rows since they are expected to happen.

Figure 5.1. Available hit policies

hit policies image 1

5.1. Hit policy examples: Decision table for discounts on movie tickets

The following is part of an example decision table for discounts on movie tickets based on customer age, student status, or military status, or all three.

Table 5.1. Example decision table for available discounts on movie tickets
Row NumberDiscount TypeDiscount

1

Senior citizen (age 60+)

10%

2

Student

10%

3

Military

10%

In this example, the total discount to be applied in the end will vary depending on the hit policy specified for the table:

  • None/Rule Order: With both None and Rule Order hit policies, all applicable rules are incorporated, in this case allowing discounts to be stacked for each customer.

    Example: A senior citizen who is also a student and a military veteran will receive all three discounts, totaling 30%.

    Key difference: With None, warnings are created for multiple rows applied. With Rule Order, those warnings are not created.

  • First Hit/Resolved Hit: With both First Hit and Resolved Hit policies, only one of the discounts can be applied.

    For First Hit, the discount that is satisfied first in the list is applied and the others are ignored.

    Example: A senior citizen who is also a student and a military veteran will receive only the senior citizen discount of 10%, since that is listed first in the table.

    For Resolved Hit, a modified table is required. The discount that you assign a priority exception to in the table, regardless of listed order, will be applied first. To assign this exception, include a new column that specifies the priority of one discount (row) over others.

    Example: If military discounts are prioritized higher than age or student discounts, despite the listed order, then a senior citizen who is also a student and a military veteran will receive only the military discount of 10%, regardless of age or student status.

    Consider the following modified decision table that accommodates a Resolved Hit policy:

    Table 5.2. Modified decision table that accommodates a Resolved Hit policy
    Row NumberDiscount TypeHas Priority over RowDiscount

    1

    Senior citizen (age 60+)

     

    10%

    2

    Student

     

    10%

    3

    Military

    1

    10%

    In this modified table, the military discount is essentially the new row 1 and therefore takes priority over both age and student discounts, and any other discounts added later. You do not need to specify priority over rows "1 and 2", only over row "1". This changes the row hit order to 3 → 1 → 2 → …​ and so on as the table grows.

    Note

    The row order would be changed in the same way if you actually moved the military discount to row 1 and applied a First Hit policy to the table instead. However, if you want the rules listed in a certain way and applied differently, such as in an alphabetized table, the Resolved Hit policy is useful.

    Key difference: With First Hit, rules are applied strictly in the listed order. With Resolved Hit, rules are applied in the listed order unless priority exceptions are specified.

  • Unique Hit: A modified table is required. With a Unique Hit policy, rows must be created in a way that it is impossible to satisfy multiple rules at one time. However, you can still specify row-by-row whether to apply one rule or multiple. In this way, with a Unique Hit policy you can make decision tables more granular and prevent overlap warnings.

    Consider the following modified decision table that accommodates a Unique Hit policy:

    Table 5.3. Modified decision table that accommodates a Unique Hit policy
    Row NumberIs Senior Citizen (age 65+)Is StudentIs MilitaryDiscount

    1

    yes

    no

    no

    10%

    2

    no

    yes

    no

    10%

    3

    no

    no

    yes

    10%

    4

    yes

    yes

    no

    20%

    5

    yes

    no

    yes

    20%

    6

    no

    yes

    yes

    20%

    7

    yes

    yes

    yes

    30%

    In this modified table, each row is unique, with no allowance of overlap, and any single discount or any combination of discounts is accommodated.

5.1.1. Types of guided decision tables

Two types of decision tables are supported in Red Hat Decision Manager: Extended entry and Limited entry tables.

  • Extended entry: An Extended Entry decision table is one for which the column definitions specify Pattern, Field, and Operator but not value. The values, or states, are themselves held in the body of the decision table.

    Extended entry
  • Limited entry: A Limited Entry decision table is one for which the column definitions specify value in addition to Pattern, Field, and Operator. The decision table states, held in the body of the table, are boolean where a positive value (a marked check box) has the effect of meaning the column should apply, or be matched. A negative value (a cleared check box) means the column does not apply.

    Limited entry

Chapter 6. Adding columns to guided decision tables

After you have created the guided decision table, you can define and add various types of columns within the guided decision tables designer.

Prerequisites

  • Any data objects that will be used for column parameters, such as Facts and Fields, have been created within the same package where the guided decision table is found, or have been imported from another package in Data ObjectsNew item of the guided decision tables designer.

For descriptions of these column parameters, see the "Required column parameters" segments for each column type in Chapter 7, Types of columns in guided decision tables.

For details about creating data objects, see Section 3.1, “Creating data objects”.

Procedure

  1. In the guided decision tables designer, click ColumnsInsert Column.
  2. Click Include advanced options to view the full list of column options.

    Figure 6.1. Add columns

    View column options in the *Add a new column* window
  3. Select the column type that you want to add, click Next, and follow the steps in the wizard to specify the data required to add the column.

    For descriptions of each column type and required parameters for setup, see Chapter 7, Types of columns in guided decision tables.

  4. Click Finish to add the configured column.

After all columns are added, you can begin adding rows of rules correlating to your columns to complete the decision table. For details, see Chapter 9, Adding rows and defining rules in guided decision tables.

The following is an example decision table for a loan application decision service:

Figure 6.2. Example of complete guided decision table

Example of complete guided decision table

Chapter 7. Types of columns in guided decision tables

The Add a new column wizard for guided decision tables provides the following column options. (Select Include advanced options to view all options.)

These column types and the parameters required for each in the Add a new column wizard are described in the sections that follow.

IMPORTANT: Required data objects for column parameters

Some of the column parameters described in this section, such as Fact Patterns and Fields, provide drop-down options consisting only of data objects already defined within the same package where the guided decision table is found. Available data objects for the package are listed in the Data Objects panel of the Project Explorer and in the Data Objects tab of the guided decision tables designer. You can create additional data objects within the package as needed, or import them from another package in Data ObjectsNew item of the guided decision tables designer. For details about creating data objects, see Section 3.1, “Creating data objects”.

7.1. "Add a Condition"

Conditions represent fact patterns defined in the left ("WHEN") portion of a rule. With this column option, you can define one or more condition columns that check for the presence or absence of data objects with certain field values, and that affect the action ("THEN") portion of the rule. You can define a binding for the fact in the condition table, or select one that has previously been defined. You can also choose to negate the pattern.

Example rule conditions

when
  $i : IncomeSource( type == "Asset" ) // Binds the IncomeSource object to the $i variable
then
  ...
end

when
  not IncomeSource( type == "Asset" ) // Negates matching pattern
then
  ...
end

After a binding is specified, you can define field constraints. If two or more columns are defined using the same fact pattern binding, the field constraints become composite field constraints on the same pattern. If you define multiple bindings for a single model class, each binding becomes a separate model class in the condition ("WHEN") side of the rule.

Required column parameters

The following parameters are required in the Add a new column wizard to set up this column type:

  • Pattern: Select from the list of fact patterns already used in conditions in your table or create a new fact pattern. A fact pattern is a combination of an available data object in the package (see the note on Required data objects for details) and a model class binding that you specify. (Examples: LoanApplication [application] or IncomeSource [income] where the bracketed portion is the binding to the given fact type)
  • Entry point: Define the entry point for the fact pattern, if applicable. An entry point is a gate or stream through which facts enter the decision engine, if specified. (Examples: Application Stream, Credit Check Stream)
  • Calculation type: Select one of the following calculation types:

    • Literal value: The value in the cell will be compared with the field using the operator.
    • Formula: The expression in the cell will be evaluated and then compared with the field.
    • Predicate: No field is needed; the expression will be evaluated to true or false.
  • Field: Select a field from the previously specified fact pattern. The field options are defined in the fact file in the Data Objects panel of your project. (Examples: amount or lengthYears fields within the LoanApplication fact type)
  • Binding (optional): Define a binding for the previously selected field, if needed. (Example: For pattern LoanApplication [application], field amount, and operator equal to, if binding is set to $amount, the end condition will be application : LoanAppplication($amount : amount == [value]).)
  • Operator: Select the operator to be applied to the fact pattern and field previously specified.
  • Value list (optional): Enter a list of value options, delimited by a comma and space, to limit table input data for the condition ("WHEN") portion of the rule. When this value list is defined, the values will be provided in the table cells for that column as a drop-down list, from which users can select only one option. (Example list: Monday, Wednesday, Friday to specify only these three options)
  • Default value (optional): Select one of the previously defined value options as the default value that will appear in the cell automatically in a new row. If the default value is not specified, the table cell will be blank by default. You can also select a default value from any previously configured data enumerations in the project, listed in the Enumeration Definitions panel of the Project Explorer. (You can create enumerations in MenuDesignProjects[select project]Add AssetEnumeration.)
  • Header (description): Add header text for the column.
  • Hide column: Select this to hide the column, or clear this to display the column.

7.1.1. Inserting an any other value in condition column cells

For simple condition columns in guided decision tables, you can apply an any other value to table cells within the column if the following parameters are set:

  • Calculation type for the condition column has been set to Literal value.
  • Operator has been set as equality == or inequality !=.

The any other value enables a rule to be defined for any other field values not explicitly defined in the rules already in the table. In the DRL source, any other is notated as not in.

Example rule condition with not in used for any other

when
  IncomeSource( type not in ("Asset", "Job") )
  ...
then
  ...
end

Procedure

  1. Select a cell of a condition column that uses the == or != operator.
  2. In the upper-right toolbar of the table designer, click EditInsert "any other" value.

7.2. "Add a Condition BRL fragment"

A Business Rule Language (BRL) fragment is a section of a rule created using the guided rules designer. The condition BRL fragment is the "WHEN" portion of the rule, and the action BRL fragment is the "THEN" portion of the rule. With this column option, you can define a condition BRL fragment to be used in the left ("WHEN") side of a rule. Simpler column types can refer to Facts and Fact fields bound in the BRL fragment and vice-versa.

The following example is a condition BRL fragment for a loan application:

Figure 7.1. Add a condition BRL fragment with the embedded guided rules designer

Condition BRL Fragment column for guided decision tables designer

You can also select Free form DRL from the list of condition options to define the condition BRL fragment without the embedded guided rules designer.

Figure 7.2. Add a condition BRL fragment with free form DRL

Condition BRL Fragment column for guided decision tables designer
Condition BRL Fragment column for guided decision tables designer
Template keys

When you add a field for a condition BRL fragment, one of the value options is Template key (as opposed to Literal or Formula). Template keys are placeholder variables that are interchanged with a specified value when the guided decision table is generated, and form separate columns in the table for each template key value specified. While Literal and Formula values are static in a decision table, Template key values can be modified as needed.

In the embedded guided rules designer, you can add a template key value to a field by selecting the Template key field option and entering the value in the editor in the format $key. For example, $age creates an $age column in the decision table.

In free form DRL, you can add a template key value to facts in the format @{key}. For example, Person( age > @{age} ) creates an $age column in the decision table.

The data type is String for new columns added using template keys.

Required column parameters

The following parameters are required in the Add a new column wizard to set up this column type:

  • Rule Modeller: Define the condition BRL fragment ("WHEN" portion) for the rule.
  • Header (description): Add header text for the column.
  • Hide column: Select this to hide the column, or clear this to display the column.

7.3. "Add a Metadata column"

With this column option, you can define a metadata element as a column in your decision table. Each column represents the normal metadata annotation in DRL rules. By default, the metadata column is hidden. To display the column, click Edit Columns in the guided decision tables designer and clear the Hide column check box.

Required column parameter

The following parameter is required in the Add a new column wizard to set up this column type:

  • Metadata: Enter the name of the metadata item in Java variable form (that is, it cannot start with a number or contain spaces or special characters).

7.4. "Add an Action BRL fragment"

A Business Rule Language (BRL) fragment is a section of a rule created using the guided rules designer. The condition BRL fragment is the "WHEN" portion of the rule, and the action BRL fragment is the "THEN" portion of the rule. With this column option you can define an action BRL fragment to be used in the right ("THEN") side of a rule. Simpler column types can refer to Facts and Fact fields bound in the BRL fragment and vice-versa.

The following example is an action BRL fragment for a loan application:

Figure 7.3. Add an action BRL fragment with the embedded guided rules designer

Action BRL Fragment in the guided decision tables designer

You can also select Add free form DRL from the list of action options to define the action BRL fragment without the embedded guided rules designer.

Figure 7.4. Add an action BRL fragment with free form DRL

Action BRL Fragment column for guided decision tables designer
Action BRL Fragment column for guided decision tables designer
Template keys

When you add a field for an action BRL fragment, one of the value options is Template key (as opposed to Literal or Formula). Template keys are placeholder variables that are interchanged with a specified value when the guided decision table is generated, and form separate columns in the table for each template key value specified. While Literal and Formula values are static in a decision table, Template key values can be modified as needed.

In the embedded guided rules designer, you can add a template key value to a field by selecting the Template key field option and entering the value in the editor in the format $key. For example, $age creates an $age column in the decision table.

In free form DRL, you can add a template key value to facts in the format @{key}. For example, Person( age > @{age} ) creates an $age column in the decision table.

The data type is String for new columns added using template keys.

Required column parameters

The following parameters are required in the Add a new column wizard to set up this column type:

  • Rule Modeller: Define the action BRL fragment ("THEN" portion) for the rule.
  • Header (description): Add header text for the column.
  • Hide column: Select this to hide the column, or clear this to display the column.

7.5. "Add an Attribute column"

With this column option, you can add one or more attribute columns representing any of the DRL rule attributes, such as Saliance, Enabled, Date-Effective, and others.

For example, the following guided decision table uses the salience attribute to specify rule priority and the enabled attribute to enable or disable rules for evaluation. Rules with a higher salience value are evaluated first, and rules with the enabled attribute are evaluated only if the check box is selected.

Figure 7.5. Example rules with salience and enabled attributes to define evaluation behavior

Guided decision table with `salience` and `enabled` attributes

Example rule source with the rule attributes

rule "Row 1 Pricing loans"
  salience 100
  enabled true
  when
    ...
  then
    ...
end
...
rule "Row 3 Pricing loans"
  enabled false
  when
    ...
  then
    ...
end

For descriptions of each attribute, select the attribute from the list in the wizard.

Hit policies and attributes

Note that depending on the hit policy that you have defined for the decision table, some attributes may be disabled because they are internally used by the hit policy. For example, if you have assigned the Resolved Hit policy to this table so that rows (rules) are applied according to a priority order specified in the table, then the Salience attribute would be obsolete. The reason is that the Salience attribute escalates rule priority according to a defined salience value, and that value would be overridden by the Resolved Hit policy in the table.

Required Column Parameter

The following parameter is required in the Add a new column wizard to set up this column type:

  • Attribute: Select the attribute to be applied to the column.

7.6. "Delete an existing fact"

With this column option, you can implement an action to delete a fact that was added previously as a fact pattern in the table. When this column is created, the fact types are provided in the table cells for that column as a drop-down list, from which users can select only one option.

Required column parameters

The following parameters are required in the Add a new column wizard to set up this column type:

  • Header (description): Add header text for the column.
  • Hide column: Select this to hide the column, or clear this to display the column.

7.7. "Execute a Work Item"

With this column option, you can execute a work item handler, based on your predefined work item definitions in Business Central. (You can create work items in MenuDesignProjects[select project]Add AssetWork Item definition.)

Required column parameters

The following parameters are required in the Add a new column wizard to set up this column type:

  • Work Item: Select from the list of your predefined work items.
  • Header (description): Add header text for the column.
  • Hide column: Select this to hide the column, or clear this to display the column.

7.8. "Set the value of a field"

With this column option, you can implement an action to set the value of a field on a previously bound fact for the "THEN" portion of the rule. You have the option to notify the decision engine of the modified values which could lead to other rules being reactivated.

Required column parameters

The following parameters are required in the Add a new column wizard to set up this column type:

  • Pattern: Select from the list of fact patterns already used in conditions or condition BRL fragments in your table or create a new fact pattern. A fact pattern is a combination of an available data object in the package (see the note on Required data objects for details) and a model class binding that you specify. (Examples: LoanApplication [application] or IncomeSource [income] where the bracketed portion is the binding to the given fact type)
  • Field: Select a field from the previously specified fact pattern. The field options are defined in the fact file in the Data Objects panel of your project. (Examples: amount or lengthYears fields within the LoanApplication fact type)
  • Value list (optional): Enter a list of value options, delimited by a comma and space, to limit table input data for the action ("THEN") portion of the rule. When this value list is defined, the values will be provided in the table cells for that column as a drop-down list, from which users can select only one option. (Example list: Accepted, Declined, Pending)
  • Default value (optional): Select one of the previously defined value options as the default value that will appear in the cell automatically in a new row. If the default value is not specified, the table cell will be blank by default. You can also select a default value from any previously configured data enumerations in the project, listed in the Enumeration Definitions panel of the Project Explorer. (You can create enumerations in MenuDesignProjects[select project]Add AssetEnumeration.)
  • Header (description): Add header text for the column.
  • Hide column: Select this to hide the column, or clear this to display the column.
  • Logically insert: This option appears when the selected Fact Pattern is not currently used in another column in the guided decision table (see the next field description). Select this to insert the fact pattern logically into the decision engine, or clear this to insert it regularly. 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 asserted the facts in the first place are no longer true.
  • Update engine with changes: This option appears when the selected Fact Pattern is already used in another column in the guided decision table. Select this to update the decision engine with the modified field values, or clear this to not update the decision engine.

7.9. "Set the value of a field with a Work Item result"

With this column option, you can implement an action to set the value of a previously defined fact field to the value of a result of a work item handler for the "THEN" portion of the rule. The work item must define a result parameter of the same data type as a field on a bound fact in order for you to set the field to the return parameter. (You can create work items in MenuDesignProjects[select project]Add AssetWork Item definition.)

An Execute a Work Item column must already be created in the table for this column option to be created.

Required column parameters

The following parameters are required in the Add a new column wizard to set up this column type:

  • Pattern: Select from the list of fact patterns already used in your table or create a new fact pattern. A fact pattern is a combination of an available data object in the package (see the note on Required data objects for details) and a model class binding that you specify. (Examples: LoanApplication [application] or IncomeSource [income] where the bracketed portion is the binding to the given fact type)
  • Field: Select a field from the previously specified fact pattern. The field options are defined in the fact file in the Data Objects panel of your project. (Examples: amount or lengthYears fields within the LoanApplication fact type)
  • Work Item: Select from the list of your predefined work items. (The work item must define a result parameter of the same data type as a field on a bound fact in order for you to set the field to the return parameter.)
  • Header (description): Add header text for the column.
  • Hide column: Select this to hide the column, or clear this to display the column.
  • Logically insert: This option appears when the selected Fact Pattern is not currently used in another column in the guided decision table (see the next field description). Select this to insert the fact pattern logically into the decision engine, or clear this to insert it regularly. 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 asserted the facts in the first place are no longer true.
  • Update engine with changes: This option appears when the selected Fact Pattern is already used in another column in the guided decision table. Select this to update the decision engine with the modified field values, or clear this to not update the decision engine.

Chapter 8. Editing or deleting columns in guided decision tables

You can edit or delete the columns you have created at any time in the guided decision tables designer.

Procedure

  1. In the guided decision tables designer, click Columns.
  2. Expand the appropriate section and click Edit or Delete next to the column name.

    Figure 8.1. Edit or delete columns

    Edit or delete columns in the guided decision tables designer.
    Note

    A condition column cannot be deleted if an existing action column uses the same pattern-matching parameters as the condition column.

  3. After any column changes, click Finish in the wizard to save.

Chapter 9. Adding rows and defining rules in guided decision tables

After you have created your columns in the guided decision table, you can add rows and define rules within the guided decision tables designer.

Prerequisites

Procedure

  1. In the guided decision tables designer, click InsertAppend row or one of the Insert row options. (You can also click Insert column to open the column wizard and define a new column.)

    Figure 9.1. Add Rows

    Add rows in the guided decision tables designer
  2. Double-click each cell and enter data. For cells with specified values, select from the cell drop-down options.

    Figure 9.2. Enter input data in each cell

    Enter data in individual cells
  3. After you define all rows of data in the guided decision table, click Validate in the upper-right toolbar of the guided decision tables designer to validate the table. If the table validation fails, address any problems described in the error message, review all components in the table, and try again to validate the table until the table passes.

    Note

    Although guided decision tables have real-time verification and validation, you should still manually validate the completed decision table to ensure optimal results.

  4. Click Save in the table designer to save your changes.

    After you define your guided decision table contents, in the upper-right corner of the guided decision tables designer, you can use the search bar if needed to search for text that appears in your guided decision table. The search feature is especially helpful in complex guided decision tables with many values:

    Figure 9.3. Search guided decision table contents

    Search guided decision table contents

Chapter 10. Defining enumerations for drop-down lists in rule assets

Enumeration definitions in Business Central determine the possible values of fields for conditions or actions in guided rules, guided rule templates, and guided decision tables. An enumeration definition contains a fact.field mapping to a list of supported values that are displayed as a drop-down list in the relevant field of a rule asset. When a user selects a field that is based on the same fact and field as the enumeration definition, the drop-down list of defined values is displayed.

You can define enumerations in Business Central or in the DRL source for your Red Hat Decision Manager project.

Procedure

  1. In Business Central, go to MenuDesignProjects and click the project name.
  2. Click Add AssetEnumeration.
  3. Enter an informative Enumeration name and select the appropriate Package. The package that you specify must be the same package where the required data objects and relevant rule assets have been assigned or will be assigned.
  4. Click Ok to create the enumeration.

    The new enumeration is now listed in the Enumeration Definitions panel of the Project Explorer.

  5. In the Model tab of the enumerations designer, click Add enum and define the following values for the enumeration:

    • Fact: Specify an existing data object within the same package of your project with which you want to associate this enumeration. Open the Data Objects panel in the Project Explorer to view the available data objects, or create the relevant data object as a new asset if needed.
    • Field: Specify an existing field identifier that you defined as part of the data object that you selected for the Fact. Open the Data Objects panel in the Project Explorer to select the relevant data object and view the list of available Identifier options. You can create the relevant identifier for the data object if needed.
    • Context: Specify a list of values in the format ['string1','string2','string3'] or [integer1,integer2,integer3] that you want to map to the Fact and Field definitions. These values will be displayed as a drop-down list for the relevant field of the rule asset.

    For example, the following enumeration defines the drop-down values for applicant credit rating in a loan application decision service:

    Figure 10.1. Example enumeration for applicant credit rating in Business Central

    EnumConfig

    Example enumeration for applicant credit rating in the DRL source

    'Applicant.creditRating' : ['AA', 'OK', 'Sub prime']

    In this example, for any guided rule, guided rule template, or guided decision table that is in the same package of the project and that uses the Applicant data object and the creditRating field, the configured values are available as drop-down options:

    Figure 10.2. Example enumeration drop-down options in a guided rule or guided rule template

    EnumDropDown

    Figure 10.3. Example enumeration drop-down options in a guided decision table

    EnumDropDownGDT

10.1. Advanced enumeration options for rule assets

For advanced use cases with enumeration definitions in your Red Hat Decision Manager project, consider the following extended options for defining enumerations:

Mapping between DRL values and values in Business Central

If you want the enumeration values to appear differently or more completely in the Business Central interface than they appear in the DRL source, use a mapping in the format 'fact.field' : ['sourceValue1=UIValue1','sourceValue2=UIValue2', …​ ] for your enumeration definition values.

For example, in the following enumeration definition for loan status, the options A or D are used in the DRL file but the options Approved or Declined are displayed in Business Central:

'Loan.status' : ['A=Approved','D=Declined']
Enumeration value dependencies

If you want the selected value in one drop-down list to determine the available options in a subsequent drop-down list, use the format 'fact.fieldB[fieldA=value1]' : ['value2', 'value3', …​ ] for your enumeration definition.

For example, in the following enumeration definition for insurance policies, the policyType field accepts the values Home or Car. The type of policy that the user selects determines the policy coverage field options that are then available:

'Insurance.policyType' : ['Home', 'Car']
'Insurance.coverage[policyType=Home]' : ['property', 'liability']
'Insurance.coverage[policyType=Car]' : ['collision', 'fullCoverage']
Note

Enumeration dependencies are not applied across rule conditions and actions. For example, in this insurance policy use case, the selected policy in the rule condition does not determine the available coverage options in the rule actions, if applicable.

External data sources in enumerations

If you want to retrieve a list of enumeration values from an external data source instead of defining the values directly in the enumeration definition, on the class path of your project, add a helper class that returns a java.util.List list of strings. In the enumeration definition, instead of specifying a list of values, identify the helper class that you configured to retrieve the values externally.

For example, in the following enumeration definition for loan applicant region, instead of defining applicant regions explicitly in the format 'Applicant.region' : ['country1', 'country2', …​ ], the enumeration uses a helper class that returns the list of values defined externally:

'Applicant.region' : (new com.mycompany.DataHelper()).getListOfRegions()

In this example, a DataHelper class contains a getListOfRegions() method that returns a list of strings. The enumerations are loaded in the drop-down list for the relevant field in the rule asset.

You can also load dependent enumeration definitions dynamically from a helper class by identifying the dependent field as usual and enclosing the call to the helper class within quotation marks:

'Applicant.region[countryCode]' : '(new com.mycompany.DataHelper()).getListOfRegions("@{countryCode}")'

If you want to load all enumeration data entirely from an external data source, such as a relational database, you can implement a Java class that returns a Map<String, List<String>> map. The key of the map is the fact.field mapping and the value is a java.util.List<String> list of values.

For example, the following Java class defines loan applicant regions for the related enumeration:

public class SampleDataSource {

  public Map<String, List<String>> loadData() {
    Map data = new HashMap();

    List d = new ArrayList();
    d.add("AU");
    d.add("DE");
    d.add("ES");
    d.add("UK");
    d.add("US");
    ...
    data.put("Applicant.region", d);

    return data;
  }

}

The following enumeration definition correlates to this example Java class. The enumeration contains no references to fact or field names because they are defined in the Java class:

=(new SampleDataSource()).loadData()

The = operator enables Business Central to load all enumeration data from the helper class. The helper methods are statically evaluated when the enumeration definition is requested for use in an editor.

Note

Defining an enumeration without a fact and field definition is currently not supported in Business Central. To define the enumeration for the associated Java class in this way, use the DRL source in your Red Hat Decision Manager project.

Chapter 11. Real-time verification and validation of guided decision tables

Business Central provides a real-time verification and validation feature for guided decision tables to ensure that your tables are complete and error free. Guided decision tables are validated after each cell change. If a problem in logic is detected, an error notification appears and describes the problem.

11.1. Types of problems in guided decision tables

The validation and verification feature detects the following types of problems:

Redundancy
Redundancy occurs when two rows in a decision table execute the same consequences for the same set of facts. For example, two rows checking a client’s birthday and providing a birthday discount may result in double discount.
Subsumption

Subsumption is similar to redundancy and occurs when two rules execute the same consequences, but one executes on a subset of facts of the other. For example, consider these two rules:

  • when Person age > 10 then Increase Counter
  • when Person age > 20 then Increase Counter

In this case, if a person is 15 years old, only one rule fires and if a person is 20 years old, both rules fire. Such cases cause similar trouble during runtime as redundancy.

Conflicts

A conflicting situation occurs when two similar conditions have different consequences. Conflicts can occur between two rows (rules) or two cells in a decision table.

The following example illustrates conflict between two rows in a decision table:

  • when Deposit > 20000 then Approve Loan
  • when Deposit > 20000 then Refuse Loan

In this case, there is no way to know if the loan will be approved or not.

The following example illustrates conflict between two cells in a decision table:

  • when Age > 25
  • when Age < 25

A row with conflicting cells never executes.

Broken Unique Hit Policy

When the Unique Hit policy is applied to a decision table, only one row at a time can be executed and each row must be unique, with no overlap of conditions being met. If more than one row is executed, then the verification report identifies the broken hit policy. For example, consider the following conditions in a table that determines eligibility for a price discount:

  • when Is Student = true
  • when Is Military = true

If a customer is both a student and in the military, both conditions apply and break the Unique Hit policy. Rows in this type of table must therefore be created in a way that does not allow multiple rules to fire at one time. For details about hit policies, see Chapter 5, Hit policies for guided decision tables.

Deficiency

Deficiency is similar to a conflict and occurs the logic of a rule in a decision table is incomplete. For example, consider the following two deficient rules:

  • when Age > 20 then Approve Loan
  • when Deposit < 20000 then Refuse Loan

These two rules may lead to confusion for a person who is over 20 years old and has deposited less than 20000. You can add more constraints to avoid the conflict.

Missing Columns
When deleted columns result in incomplete or incorrect logic, rules cannot fire properly. This is detected so that you can address the missing columns, or adjust the logic to not rely on intentionally deleted conditions or actions.
Incomplete Ranges
Ranges of field values are incomplete if a table contains constraints against possible field values but does not define all possible values. The verification report identifies any incomplete ranges provided. For example, if your table has a check for if an application is approved, the verification report reminds you to make sure you also handle situations where the application was not approved.

11.2. Types of notifications

The verification and validation feature uses three types of notifications:

  • gdtValidationVerificationIconError Error: A serious problem that may lead to the guided decision table failing to work as designed at run time. Conflicts, for example, are reported as errors.
  • gdtValidationVerificationIconWarning Warning: Likely a serious problem that may not prevent the guided decision table from working but requires attention. Subsumptions, for example, are reported as warnings.
  • gdtValidationVerificationIconInfo Information: A moderate or minor problem that may not prevent the guided decision table from working but requires attention. Missing columns, for example, are reported as information.
Note

Business Central verification and validation does not prevent you from saving an incorrect change. The feature only reports issues while editing and you can still continue to overlook those and save your changes.

11.3. Disabling verification and validation of guided decision tables

The decision table verification and validation feature of Business Central is enabled by default. This feature helps you validate your guided decision tables, but with complex guided decision tables, this feature can hinder decision engine performance. You can disable this feature by setting the org.kie.verification.disable-dtable-realtime-verification system property value to true in your Red Hat Decision Manager distribution.

Procedure

Navigate to ~/standalone-full.xml and add the following system property:

<property name="org.kie.verification.disable-dtable-realtime-verification" value="true"/>

For example, on Red Hat JBoss EAP, you add this system property in $EAP_HOME/standalone/configuration/standalone-full.xml.

Chapter 12. Converting a guided decision table to a spreadsheet decision table

After you define a guided decision table in Business Central, you can convert the guided decision table to an XLS spreadsheet decision table file for offline reference and file sharing. The guided decision table must be an extended entry guided decision table in order to be converted. The conversion tool does not support limited entry guided decision tables.

For more information about spreadsheet decision tables, see Designing a decision service using spreadsheet decision tables.

Warning

Guided decision tables and spreadsheet decision tables are different decision table formats that support different features. Any supported features that differ between the two decision table formats are modified or lost when you convert one decision table format to the other.

Procedure

In Business Central, navigate to the guided decision table asset that you want to convert and in the upper-right toolbar of the decision tables designer, click Convert to XLS:

Figure 12.1. Convert an uploaded decision table

Decision table example

After the conversion, the converted decision table is then available as a spreadsheet decision table asset in your project that you can download for offline reference.

Chapter 13. 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

Procedure

  1. In Business Central, go to MenuDesignProjects and click the project name.
  2. 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.

  3. 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".

  4. 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 using ReleaseId
    • 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.6 in a client application pom.xml file:

    <!-- For local execution -->
    <dependency>
      <groupId>org.kie</groupId>
      <artifactId>kie-ci</artifactId>
      <version>7.30.0.Final-redhat-00003</version>
    </dependency>
    
    <!-- For remote execution on Decision Server -->
    <dependency>
      <groupId>org.kie.server</groupId>
      <artifactId>kie-server-client</artifactId>
      <version>7.30.0.Final-redhat-00003</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.

    Note

    Instead 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 project pom.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.6.0.redhat-00004</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?.

  5. Ensure that the dependencies for artifacts containing model classes are defined in the client application pom.xml file exactly as they appear in the pom.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 Viewpom.xml.

    For example, the following Person class dependency appears in both the client and deployed project pom.xml files:

    <dependency>
      <groupId>com.sample</groupId>
      <artifactId>Person</artifactId>
      <version>1.0.0</version>
    </dependency>
  6. If you added the slf4j dependency to the client application pom.xml file for debug logging, create a simplelogger.properties file on the relevant classpath (for example, in src/main/resources/META-INF in Maven) with the following content:

    org.slf4j.simpleLogger.defaultLogLevel=debug
  7. In your client application, create a .java main class containing the necessary imports and a main() 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 following Wage 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 needed), configure the .java class to import KIE services, a KIE container, and a KIE session, and then use the main() method to fire all rules against a defined fact model:

    Executing rules locally

    import org.kie.api.KieServices;
    import org.kie.api.builder.ReleaseId;
    import org.kie.api.runtime.KieContainer;
    import org.kie.api.runtime.KieSession;
    import org.drools.compiler.kproject.ReleaseIdImpl;
    
    public class RulesTest {
    
      public static final void main(String[] args) {
        try {
          // Identify the project in the local repository:
          ReleaseId rid = new ReleaseIdImpl("com.myspace", "MyProject", "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();
        }
      }
    }

  8. Run the configured .java class from your project directory. You can run the file in your development platform (such as Red Hat CodeReady 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
  9. 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.

13.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 the mvel-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.
Note

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 24 bound variables only (including the built-in drools variable). For example, the following rule consequence uses more than 24 bound variables and creates a compilation error:

...
then
  $input.setNo25Count(functions.sumOf(new Object[]{$no1Count_1, $no2Count_1, $no3Count_1, ..., $no25Count_1}).intValue());
  $input.getFirings().add("fired");
  update($input);

13.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

  1. In the pom.xml file of your Maven project, ensure that the packaging type is set to kjar and add the kie-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 the kie-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.30.0.Final-redhat-00003). These settings are required to properly package the Maven project.

    Note

    Instead 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 project pom.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.6.0.redhat-00004</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?.

  2. 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>
  3. 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.

13.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

  1. 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.30.0.Final-redhat-00003).

    Note

    Instead 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 project pom.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.6.0.redhat-00004</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?.

  2. Add rule assets to the KIE virtual file system KieFileSystem and use KieBuilder with buildAll( 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 resulting KieSession uses constraints based on lambda expressions instead of less-efficient mvel expressions. If buildAll() 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 a Model with a fluent API and create a KieBase 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 14. Next steps

Appendix A. Versioning information

Documentation last updated on Friday, May 22, 2020.

Legal Notice

Copyright © 2020 Red Hat, Inc.
The text of and illustrations in this document are licensed by Red Hat under a Creative Commons Attribution–Share Alike 3.0 Unported license ("CC-BY-SA"). An explanation of CC-BY-SA is available at http://creativecommons.org/licenses/by-sa/3.0/. In accordance with CC-BY-SA, if you distribute this document or an adaptation of it, you must provide the URL for the original version.
Red Hat, as the licensor of this document, waives the right to enforce, and agrees not to assert, Section 4d of CC-BY-SA to the fullest extent permitted by applicable law.
Red Hat, Red Hat Enterprise Linux, the Shadowman logo, the Red Hat logo, JBoss, OpenShift, Fedora, the Infinity logo, and RHCE are trademarks of Red Hat, Inc., registered in the United States and other countries.
Linux® is the registered trademark of Linus Torvalds in the United States and other countries.
Java® is a registered trademark of Oracle and/or its affiliates.
XFS® is a trademark of Silicon Graphics International Corp. or its subsidiaries in the United States and/or other countries.
MySQL® is a registered trademark of MySQL AB in the United States, the European Union and other countries.
Node.js® is an official trademark of Joyent. Red Hat is not formally related to or endorsed by the official Joyent Node.js open source or commercial project.
The OpenStack® Word Mark and OpenStack logo are either registered trademarks/service marks or trademarks/service marks of the OpenStack Foundation, in the United States and other countries and are used with the OpenStack Foundation's permission. We are not affiliated with, endorsed or sponsored by the OpenStack Foundation, or the OpenStack community.
All other trademarks are the property of their respective owners.
Red Hat logoGithubRedditYoutubeTwitter

Learn

Try, buy, & sell

Communities

About Red Hat Documentation

We help Red Hat users innovate and achieve their goals with our products and services with content they can trust.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. For more details, see the Red Hat Blog.

About Red Hat

We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

© 2024 Red Hat, Inc.