JBoss.orgCommunity Documentation

Chapter 4. Authoring Assets

4.1. Version management
4.2. The Asset Editor
4.3. Creating a package
4.3.1. Empty package
4.3.2. Importing DRL packages
4.4. Spring Contexts
4.5. Working Sets
4.5.1. Activating and Using Working Sets
4.6. Business rules with the guided editor
4.6.1. Parts of the Guided Rule Editor
4.6.2. The "WHEN" (left-hand side) of a Rule
4.6.3. The "THEN" (right-hand side) of a Rule
4.6.4. Optional attributes
4.6.5. Pattern/Action toolbar
4.6.6. User driven drop down lists
4.6.7. Augmenting with DSL sentences
4.6.8. A more complex example:
4.7. DSL rules
4.8. Technical rules (DRL)
4.9. Spreadsheet decision tables
4.10. Guided decision tables (web based)
4.10.1. Types of decision table
4.10.2. Main components\concepts
4.10.3. Defining a web based decision table
4.10.4. Rule definition
4.10.5. Audit Log
4.11. Templates of assets/rules
4.11.1. Creating a rule template
4.11.2. Define the template
4.11.3. Defining the template data
4.11.4. Generated DRL
4.12. The Fact Model
4.12.1. Ways to define a Fact Model
4.12.2. Creating a JAR Model
4.12.3. Declarative model
4.13. Functions
4.14. DSL editor
4.15. Rule flows
4.16. BPMN2 Process
4.17. Work Item Definition
4.18. Data enumerations (drop down list configurations)
4.18.1. Advanced enumeration concepts
4.19. Test Scenario
4.19.1. Given Section
4.19.2. Expect Section
4.19.3. Global Section
4.19.4. New Input Section
4.19.5. Audit Log
4.20. File
4.21. Change-Set
4.21.1. Change-Set Editor UI
4.21.2. Adding Packages using a Wizard
4.21.3. Adding Assets using a Wizard
4.22. Services
4.22.1. Configuring Multiple Knowledge Bases
4.22.2. Knowledge Base Configuration Panel
4.22.3. Downloading War & Managing Dependencies

Both assets and whole packages of assets are "versioned" in the Guvnor, but the mechanism is slightly different. Individual assets are saved a bit like a version of a file in a source control system. However, packages of assets are versioned "on demand" by taking a snapshot (typically which is used for deployment). The next section talks about deployment management and snapshots.


Each time you make a change to an asset, it creates a new item in the version history. This is a bit like having an unlimited undo. You can look back through the history of an individual asset like the list above, and view it (and restore it) from that point in time.

The Asset Editor is the principle component of Guvnor's User-Interface. It consists of two tabs:-

Configuring packages is generally something that is done once, and by someone with some experience with rules/models. Generally speaking, very few people will need to configure packages, and once they are setup, they can be copied over and over if needed. Package configuration is most definitely a technical task that requires the appropriate expertise.

All assets live in "packages" in the Guvnor - a package is like a folder (it also serves as a "namespace"). A home folder for rule assets to live in. Rules in particular need to know what the fact model is, what the namespace is etc.

So while rules (and assets in general) can appear in any number of categories, they only live in one package. If you think of the Guvnor as a file system, then each package is a folder, and the assets live in that folder - as one big happy list of files. When you create a deployment snapshot of a package, you are effectively copying all the assets in that "folder" into another special "folder".

To create an empty package select "New Package" from the "Create new" (asset) menu.


This textual editor allows you to define Drools (and potentially any) Spring context file. These files are later accessible through HTTP.


The editor comes with a basic pallete that you can use to paste predefined Spring Beans templates like kbases, ksessions and so on.

The pallete also has a Package tree that can be used to add resources to the Spring Context file being edited.

The Beans are inserted in the caret position of the editor

The elements in the pallete can be customized editing the file $GUVNOR_HOME/WEB-INF/Clases/springContextElements.properties


Each Spring Context has its own URL that applications can use to access it. These URLs are shown in the Package Edit Screen


Working Sets are a mean for grouping Facts and then defining constraints on them. You can create groups of Facts and only those Facts will be visible when authoring rules using the Guided Editor.

Right now, Working Sets must be activated manually from the Guided Editor window (using the "Select Working Set" button placed in the toolbar). In the future, different Working Sets could be assigned to different users to reduce the scope and complexity when authoring rules.


The figure above shows the window used to create or modify Working Sets. In this window you will find 2 lists. The list on the left side contains the possible Fact Types that can be added to the Working Set. These facts are those defined/imported in the package's model. The list on the right side contains the allowed Fact Types of this Working Set. When this Working Sets is active, only those Fact Types could be used while authoring rules using the Guided BRL Editor


Once you have selected the valid Fact Types for a Working Set, you can add Constraints to the fields of those Facts Types. The image above shows how the Field Constraint tab looks like. In this configuration screen you will find:

A.- Fact Types dropdown: Here you will find a list containing the Working Set's Fact Types

B.- Field dropdown: Once you have selected a Fact Type, this dropdown will contain its fields.

C.- Constraints List: This lists shows all the Constraints applied to the selected Field

D.- Action Buttons: Using these buttons you will be able to add or remove Constraints to the selected Field. Right now, Guvnor provides a built-in collection of Constraints. The idea for next releases is to let users to plug their custom Constraints too.

E.- Constraint's Attributes: In this section you will find all the attributes of the current Constraint that could be parametrized by the user.

In the example above, a Matches Constraint is created for Car.brand field. This means that when rule authors use this field in a Rule condition, they should use a value valid according to this constraint, otherwise they will receive an error or warning.

Working Sets are no active by default in Guvnor. Because this is an experimental feature, you must enable them manually in the Guided Editor panel if you want to use them. In the future, Working Sets will be associated to each user's profile.

A new button was added in Guided Editor's Toolbar: "Select Working Sets". This button will open a popup with the list of the package's Working Sets. Using this popup you can activate one or more Working Sets.

When Working Sets are activated, only the Fact Types allowed by them could be used when inserting new Patterns or Actions. The Patterns and Actions already present in the rule that contain prohibited Fact Types are marked as read only. Take a look at the next screen shots comparing the Guided Editor panel with and without Working Sets


In the image you can see how Working Sets could help rule's authors by reducing the amount of available Fact Types


Here you can see how Patterns containing prohibited Fact Types are switched to read only mode after Working Sets are activated.

Up to now we have only cover how Facts are filtered using Working Sets. Another important feature of Working Sets is Field Constraints. We have already saw how to configure them, now we are going to explain how to use them.

Because Field Constraints are defined inside a Working Set, we need to activate one or more Working Set to start working with them. Once a Working Set defining Field's Constraints is active we have two ways to use them: on demand validation and real-time validation.

On demand validation is performed when you press the "Verify" button present in Guided Editor's toolbar. This button will fire a rule verification and will end up showing a report with the results. Any violated constraint will be shown as an error or warning according to its relevance


The image above shows the report that appears when a Working Set defines a Range Constraint on Driver.age. The age should be between 18 and 80.

Real-Time validation is an experimental feature (yes, inside another experimental feature like Working Sets) that checks for Field's Constraints violations in real time and mark the lines where the violations are using error or warning icons. This feature is disabled by default because sometimes it could be expensive. If you want to try it out, you should enable it in Administration -> Rules Verification. This configuration is not yet persisted, so you need to enable it every time you start Guvnor.


This Image shows the result of real-time validation. There you can see the same result as on demand validation, but you don't need to click any button, and the errors/warnings are shown in a more fashionable way!

Warning

The problem with real-time validation is that right now only support "top level" Patterns.

Business Rules authored with the Guided Editor are more commonly known as "BRL Rules".

These rules use the guided GUI which controls and prompts user input based on knowledge of the object model.

This can also be augmented with DSL sentences.

B : This shows a pattern which is declaring that the rule is looking for a "LoanApplication" fact (the fields are listed below, in this case none). Another pattern, "Applicant", is listed below "LoanApplication". Fields "creditRating" and "applicationDate" are listed. Clicking on the fact name ("LoanApplication") will pop-up a list of options to add to the fact declaration:-

C : The "minus" icon ("[-]") indicates you can remove something. In this case it would remove the whole "LoanApplication" fact declaration. Depending upon the placement of the icon different components of the rule declaration can be removed, for example a Fact Pattern, Field Constraint, other Conditional Element ("exists", "not exists", "from" etc) or an Action.

D : The "plus" icon ("+") allows you to add more patterns to the condition or the action part of the rule, or more attributes. In all cases, a popup option box is provided. For the "WHEN" part of the rule, you can choose from a list of Conditional Elements to add:

If you just put a fact (like is shown above) then all the patterns are combined together so they are all true ("and").

E : This shows the constraint for the "creditRating" field. Looking from left to right you find:-

F : This shows the constraint for the "applicationDate" field. Looking from left to right you find:

H : This shows an "action" of the rule, the Right Hand Side of a rule consists in a list of actions. In this case, we are updating the "explanation" field of the "LoanApplication" fact. There are quite a few other types of actions you can use:-


In the above example, you can see how to use a mixture of Conditional Elements, literal values, and formulas. The rule has 4 "top level" Patterns and 1 Action. The "top level" Patterns are:

  1. A Fact Pattern on Person. This Pattern contains two field constraints: one for birthDate field and the other one is a formula. Note that the value of the birthDate restriction is selected from a calendar. Another thing to note is that you can make calculations and use nested fields in the formula restriction (i.e. car.brand). Finally, we are setting a variable name ($p) to the Person Fact Type. You can then use this variable in other Patterns.

    Note

    The generated DRL from this Pattern will be:

    $p : Person( birthDate < "19-Dec-1982" , eval( car.brand == "Ford" && salary > (2500 * 4.1) ))
  2. A From Pattern. This condition will create a match for every Address whose street name is "Elm St." from the Person's list of addresses. The left side of the from is a regular Fact Pattern and the right side is an Expression Builder that let us inspect variable's fields.

    Note

    The generated DRL from this Pattern will be: Address( street == "Elm St." ) from $p.addresses

  3. A "Not Exist" Conditional Element. This condition will match when its content doesn't create a match. In this case, its content is a regular Fact Pattern (on Person). In this Fact Pattern you can see how variables ($p) could be used inside a formula value.

    Note

    The generated DRL from this Pattern will be: not Person( salary == ( $p.salary * 2 ) )

  4. A "From Accumulate" Conditional Element. This is maybe one of the most complex Patterns you can use. It consist in a Left Pattern (It must be a Fact Pattern. In this case is a Number Pattern. The Number is named $totalAddresses), a Source Pattern (Which could be a Fact Pattern, From, Collect or Accumulate conditional elements. In this case is an Address Pattern Restriction with a field restriction in its zip field) and a Formula Section where you can use any built-in or custom Accumulate Function (in this example a count() function is used). Basically, this Conditional Element will count the addresses having a zip code of 43240 from the Person's list of addresses.

    Note

    The generated DRL from this Pattern will be: $totalAddresses : Number() from accumulate ($a : Address( zipCode == " 43240") from $p.addresses, count($a))

DSL rules are textual rules, that use a language configuration asset to control how they appear.


A dsl rule is a single rule. Referring to the picture above, you can a text editor. You can use the icons to the right to provide lists of conditions and actions to choose from (or else press Control + Space at the same time to pop up a list).

Technical (DRL) rules are stored as text - they can be managed in the Guvnor. A DRL can either be a whole chunk of rules, or an individual rule. if its an individual rule, no package statement or imports are required (in fact, you can skip the "rule" statement altogether, just use "when" and "then" to mark the condition and action sections respectively). Normally you would use the IDE to edit raw DRL files, since it has all the advanced tooling and content assistance and debugging. However, there are times when a rule may have to deal with something fairly technical in a package in Guvnor. In any typical package of rules, you generally have a need for some "technical rules" - you can mix and match all the rule types together of course.


Multiple rules can be stored in a spreadsheet. Each row in the spreadsheet is a rule, and each column is either a condition, an action, or an option. The Drools Expert User Guide discusses spreadsheet decision tables in more detail.


To use a spreadsheet, you upload an XLS file (and can download the current version, as per the picture above). To create a new decision table, when you launch the rule wizard, you will get an option to create one (after that point, you can upload the XLS file).

The guided decision table feature allows decision tables to be edited in place on the web. This works similar to the guided editor by introspecting what facts and fields are available to guide the creation of a decision table. Rule attributes, meta-data, conditions and actions can be defined in a tabular format thus facilitating rapid entry of large sets of related rules. Web-based decision table rules are compiled into DRL like all other rule assets.

The guided decision table is split into two main sections:-


When a new empty decision table has been created you need to define columns for Facts, their constraints and corresponding actions.

Expand the "Decision table" element and you will see three further sections for "Conditions", "Actions" and "Options". Expanding either the "Conditions" or "Actions" sections reveals the "New column" icon. This can be used to add new column definitions to the corresponding section. Existing columns can be removed by clicking the "-" icon beside each column name, or edited by clicking the "pencil" icon also beside each column name. The "Options" section functions slightly differently however the principle is the same: clicking the "Add Attribute/Metadata" icon allows columns for table attributes to be defined (such as "salience", "no-loop" etc) or metadata added.


A Wizard can also be used to assist with defining the decision table columns.

The wizard can be chosen when first electing to create a new rule. The wizard provides a number of pages to define the table:-

The guided rule editor is great when you need to define a single rule, however if you need to define multiple rules following the same structure but with different values in field constraints or action sections a "Rule Template" is a valuable asset. Rule templates allow the user to define a rule structure with place-holders for values that are to be interpolated from a table of data. Literal values, formulae and expressions can also continue to be used.

Rule Templates can often be used as an alternative for Decision Tables in Drools Guvnor.

When you have completed the definition of your rule template you need to enter the data that will be used to interpolate the "Template Key" place-holders. Drools Guvnor provides the facility to enter data in a flexible grid within the guided editor screen. The grid editor can be launched by pressing the "Load Template Data" button on the guided editor screen.

The rule template data grid is very flexible; with different pop-up editors for the underlying fields' data-types. Columns can be resized and sorted; and cells can be merged and grouped to facilitate rapid data entry.

One row of data interpolates the "Template Key" place-holders for a single rule; thus one row becomes one rule.


For any rule base application, a fact model is needed to drive the rules. The fact model typically overlaps with the applications domain model, but in general it will be decoupled from it (as it makes the rules easier to manage over time). There are no technical limitations on using your domain model as your fact model, however this introduces tighter coupling between your business domain (domain model) and your knowledge domain (fact model). Consequentially if your domain model were to change you would need to, at the very least, revisit your rule definitions.

Why would you chose declared types over JAR files: generally this reinforces the fact that the model "belongs" to the KnowledgeBase, rather then the application, and allows the model to have a lifecycle separate from the application. It also allows Java types to be enriched with Rule specific annotations. Additionally it also removes the burden of keeping JAR files synchronised between rules and the applications that use the rules.

Declarative models can be either:-

Creating a Declarative Model is a two step process.

Once the Declarative Model asset has been created you are presented with the initial modelling screen; that is empty to begin.


Facts, being semantically equivalent to Java classes, can be created by selecting the "Add new fact type" button. An existing Fact definition can be edited by clicking the "pencil" icon on the same row as the Fact name. Furthermore existing Facts can be deleted by clicking the "[-]" icon.



Fact Fields can be created by selecting the "Add field" button. The type of a field is suggested by a list (but this list is not exhaustive). An existing Fact Field definition can be edited by clicking the "pencil" icon on the same row as the Fact Field name. Furthermore existing Fact Fields can be deleted by clicking the "[-]" icon.


Fact annotations can be created by selecting the "Add annotation" button. Annotations are listed under the Fact title, before the fields, by convention. Annotations are prefixed with the "@" symbol. This not only makes them instantly recognisable but is also consistent with their definition in DRL.

The annotation "Name" and "Value" are mandatory whereas the "Key" is optional. If a "Key" is not given a default value of "value" will be assigned. This is consistent with how annotations are held within Drools Expert.

An existing Fact Annotation can be edited by clicking the "pencil" icon on the same row as the Fact Annotation name. Furthermore existing Fact Annotations can be deleted by clicking the "[-]" icon.



Declarative types can extend existing:-



Functions are another asset type. They are NOT rules, and should only be used when necessary. The function editor is a textual editor. Functions


The DSL editor allows DSL Sentences to be authored. The reader should take time to explore DSL features in the Drools Expert documentation; as the syntax in Guvnor's DSL Editor is identical. The normal syntax is extended to provide "hints" to control how the DSL variable is rendered and validated within the user-interface.

The following "hints" are supported:-


Rule flows: Rule flows allow you to visually describe the steps taken - so not all rules are evaluated at once, but there is a flow of logic. Rule flows are not covered in this chapter on the Guvnor, but you can use the IDE to graphically draw ruleflows, and upload the .rfm file to the Guvnor.

Similar to spreadsheets, you upload/download ruleflow files (the eclipse IDE has a graphical editor for them). The details of Rule Flows are not discussed here.

Check the jBPM documentation: Chapter 10. Designer, for more information.

Check the jBPM documentation: Chapter 10. Designer, for more information.

Data enumerations are an optional asset type that technical folk can configure to provide drop down lists for the guided editor. These are stored and edited just like any other asset, and apply to the package that they belong to.

The contents of an enum config are a mapping of Fact.field to a list of values to be used in a drop down. That list can either be literal, or use a utility class (which you put on the classpath) to load a list of strings. The strings are either a value to be shown on a drop down, or a mapping from the code value (what ends up used in the rule) and a display value (see the example below, using the '=').


In the above diagram - the "MM" indicates a value that will be used in the rule, yet "Mini Mal" will be displayed in the GUI.

Getting data lists from external data sources: It is possible to have the Guvnor call a piece of code which will load a list of Strings. To do this, you will need a bit of code that returns a java.util.List (of String's) to be on the classpath of the Guvnor. Instead of specifying a list of values in the Guvnor itself - the code can return the list of Strings (you can use the "=" inside the strings if you want to use a different display value to the rule value, as normal). For example, in the 'Person.age' line above, you could change it to:

 'Person.age' : (new com.yourco.DataHelper()).getListOfAges()

This assumes you have a class called "DataHelper" which has a method "getListOfAges()" which returns a List of strings (and is on the classpath). You can of course mix these "dynamic" enumerations with fixed lists. You could for example load from a database using JDBC. The data enumerations are loaded the first time you use the guided editor in a session. If you have any guided editor sessions open - you will need to close and then open the rule to see the change. To check the enumeration is loaded - if you go to the Package configuration screen, you can "save and validate" the package - this will check it and provide any error feedback.

There are a few other advanced things you can do with data enumerations.

Drop down lists that depend on field values: Lets imagine a simple fact model, we have a class called Vehicle, which has 2 fields: "engineType" and "fuelType". We want to have a choice for the "engineType" of "Petrol" or "Diesel". Now, obviously the choice type for fuel must be dependent on the engine type (so for Petrol we have ULP and PULP, and for Diesel we have BIO and NORMAL). We can express this dependency in an enumeration as:

'Vehicle.engineType' : ['Petrol', 'Diesel']
'Vehicle.fuelType[engineType=Petrol]' : ['ULP', 'PULP' ]
'Vehicle.fuelType[engineType=Diesel]' : ['BIO', 'NORMAL' ]

This shows how it is possible to make the choices dependent on other field values. Note that once you pick the engineType, the choice list for the fuelType will be determined.

Loading enums programmatically: In some cases, people may want to load their enumeration data entirely from external data source (such as a relational database). To do this, you can implement a class that returns a Map. The key of the map is a string (which is the Fact.field name as shown above), and the value is a java.util.List of Strings.

public class SampleDataSource2 {


  public Map<String>, List<String> loadData() {
    Map data = new HashMap();
    List d = new ArrayList();
    d.add("value1");
    d.add("value2");
    data.put("Fact.field", d);
    return data;
 }
}

And in the enumeration in the BRMS, you put:

=(new SampleDataSource2()).loadData()

The "=" tells it to load the data by executing your code.

Mode advanced enumerations: In the above cases, the values in the lists are calculated up front. This is fine for relatively static data, or small amounts of data. Imagine a scenario where you have lists of countries, each country has a list of states, each state has a list of localities, each locality has a list of streets and so on... You can see how this is a lot of data, and it can not be loaded up. The lists should be loaded dependent on what country was selected etc...

Well the above can be addressed in the following fashion:

'Fact.field[dependentField1, dependentField2]' : '(new com.yourco.DataHelper()).getListOfAges("@{dependentField1}", "@{dependentField2}")'

Similar to above, but note that we have just specified what fields are needed, and also on the right of the ":" there are quotes around the expression. This expression will then be evaluated, only when needed, substituting the values from the fields specified. This means you can use the field values from the GUI to drive a database query, and drill down into data etc. When the drop down is loaded, or the rule loaded, it will refresh the list based on the fields. 'dependentField1' and 'dependentField2' are names of fields on the 'Fact' type - these are used to calculate the list of values which will be shown in a drop down if values for the "field".

Test Scenarios are used to validate that rules and knowledge base work as expected. When the knowledge base evolves, Test Scenarios guard against regression.


Given section lists the facts needed for the behaviour. Expect section lists the expected changes and actions done by the behaviour. Given facts are passed for the Test Scenario before execution. During the rule execution, changes in the knowledge base are recorded. After the execution ends the recorded actions, existing facts in the knowledge base and knowledge base output is compared against the expectations.


Files can be stored in Guvnor as assets.

You need to provide the asset name and file extension in the "New Asset" popup dialog.


Once you have created the asset a screen to upload (or download) the file itself is shown.


If you specify a file extension of "properties" a standard Java properties file can also be created.


The properties name\value pairs can be maintained from within Guvnor.


Change-set is one of the ways Drools has to group one or more Assets in a single Asset. Change-sets can then be added to a Knowledge Builder or a Knowledge Agent to process all the assets referenced by it.

By default, Guvnor provides a unique Change-Set per package containing the package binary or the drl source. The main problem with this is when you want to use just a sub-set of assets of a package (or even from different packages) in your application.

Using the Change-Set editor you can define your own change-sets inside Guvnor in any way you want. You could have a combination of different assets and packages, or even different snapshots of a package in a change-set. You can have all the change-sets per package you need, so if different applications are using the same package in different ways (different assets or assets' versions of a same package) you can make use of this feature of Guvnor.

Service Config is a special asset that defines an execution service configuration. This execution service is a war file (generated automatically by the editor) which you can deploy to execute KnowledgeBases remotely for any sort of client application. As this service is stateless, it is possible to have as many of these services deployed as you need to serve the client load.

This version of the execution server supports as many Knowledge Bases as you need, supporting also multiple stateless and stateful sessions in a native way.

To create a new Service you have to go to "Create New" -> "New Service Config" option in Knowledge Base section of Guvnor. In the following sections you have detailed information on how to configure your Service Config.



In the above configuration panel you have 6 items that you can interact with:

  1. Add Asset Button: add new assets to the tree using a wizard. See next section for further information.

  2. Remove Selected Button: remove the selected assets (the ones that are checked) from Assets Tree.

  3. Rename KBase Button: this button will open a standard “prompt for rename” dialog box.

  4. Advanced Options Button: opens the advanced knowledge base configuration dialog. Configurations that are not available in the panel, should be available in this advanced dialog. Detailed information about it can be found in the "Advanced Knowledge Base Configuration Options" section.

  5. Assets Tree: Here you have the complete set of assets, grouped by package and type, that are referenced by the active knowledge base configuration. For additional information, please read the "Assets Tree" section.

  6. Sessions Grid: Here users can create, delete and edit in place a list of desires ksessions. For detailed instructions on how to configure ksessions, please check the "Configuring Knowledge Sessions" section.


The ksessions grid is composed by the following columns:

  1. Add and Remove Icons: Users can use these icons to add new or remove existing knowledge sessions. Important to note that should exists at least one knowledge session.

  2. Knowledge Session Name: Defines the ksession name. Users can edit this particular field in place as highlighted on box "A".

  3. Session Type: Defines if a ksession is Stateless or Stateful. Users can also select the desired type directly on the grid.

  4. Configuration Button: This button opens the knowledge session configuration dialog. See next section for further information.

After configuring your knowledge bases and sessions, you're ready to download the service war. For so, all you need to do is click on the "Download War" button and the following screen (or a similar one, depending on your browser) will show up.


Warning

Before click on the "Download War" button, makes sure that you don't have pending changes. This is a very important step, once the the war file is generated based on the latest saved information and not on the current screen state.

The generated file is a ready to be deployed war file. Which mean that it contains all the necessary configuration files and all the needed dependencies as well. As dependency management is a crucial subject in a real world applications deployment, we will discuss that in more detail in the next section.