Skip Headers
Oracle® Business Rules User's Guide
10g (10.1.3.1.0)

Part Number B28965-02
Go to Documentation Home
Home
Go to Book List
Book List
Go to Table of Contents
Contents
Go to Index
Index
Go to Feedback page
Contact Us

Go to previous page
Previous
Go to next page
Next
View PDF

4 Using XML Facts with Rule Author

This chapter provides a tutorial for working with Oracle Business Rules using XML documents (facts that are supplied in an XML document). This chapter also shows you how to create a rule-enabled Java application that uses XML.

In the rules XML How-To, driver data is supplied in an XML document that specifies driver information, and the business rules we develop in this chapter determine if a rental company service representative should decline to rent a vehicle due to driver age restrictions (according to rental company business policies that we define).

This chapter includes the following sections:


Note:

We call the sample application in this chapter the rules XML How-To. This sample application is available in the Oracle Business Rules area, under the Viewlets and Tutorials heading on the Oracle Technology Web site:

http://www.oracle.com/technology/products/ias/business_rules/files/how-to-rules-xml.zip


4.1 Overview of Using XML Documents and Schemas with Rule Author

Rule Author lets you import XML elements into a data model and lets you write rules using the XML elements in conditional expressions. For example, if you have an XML document that contains data associated with your application, and you have the schema associated with the XML document, then you can use Rule Author to define rules based on elements that you specify from the XML schema.

When you start with an XML schema, using XML documents with Rule Author involves the following steps:

  1. Rule Author generates Java classes from the XML schema by running the supplied Java Architecture for XML Binding (JAXB) compiler to generate JAXB packages, classes, and interfaces for the XML schema.

  2. You import XML elements into the data model in a dictionary.

  3. You define rules that specify business policies based on the XML elements from an XML document. The process of writing rules for XML documents is very similar to writing rules for Java objects.

After you finish using Rule Author to create the rules, you can write an application that uses the rules with XML documents. To accomplish XML document processing, you assert elements of an XML document into a Rules Engine session.


Note:

To use a JAXB binding compiler that is different from the implementation supplied with Rule Author, you can manually perform the XML schema processing using your JAXB binding compiler and then import the generated Java packages and classes into the data model.

For more information about JAXB, see

http://java.sun.com/webservices/jaxb/

4.2 Creating a Rule Author User and Starting Rule Author

Start Rule Author by entering the URL for the home page. The URL for the home page typically includes the name of the host computer and the port number assigned to the application server during the installation, plus the path of the Rule Author home page.


See Also:

"Creating a Rule Author User" for more information

4.3 Creating and Saving a Dictionary for the XML Car Rental Sample

To work with Rule Author, you must start with a dictionary. Rule Author stores rules and their associated definitions in a dictionary. To create or save a dictionary, you must connect to a repository that stores the dictionary. As shipped, Rule Author supports two types of repositories: WebDAV (Web Distributed Authoring and Versioning) and file repository.

In this section, you create and save a dictionary for the XML How-To using a WebDAV repository.


Note:

To create the dictionary shown in this chapter, you can either create a new dictionary (using either a WebDAV repository or a file repository) or you can load the completed dictionary from the $HowToDir/dict directory supplied with the How-To, where $HowToDir is the directory where you installed the XML How-To.

This section covers the following topics:

4.3.1 Connecting to a Rule Author Repository

In Oracle Business Rules, a dictionary stores rules and the data model associated with the rules.


Note:

Regardless of whether you choose to use a WebDAV or file repository, the repository must exist before you can connect to it. See Appendix B, "Using Rule Author and Rules SDK with Repositories" for more information.

To connect to a repository, do the following:

  1. Click the Repository tab.

  2. Click the Connect secondary tab.

  3. In the Repository Type field select the WebDAV repository type.

  4. Enter the URL to the WebDAV repository (see Figure 4-1). The URL must be in the form:

    http://www.fully_qualified_host_name.com:7777/repository_name
    

    Note:

    In order for authentication to work, you must use a fully qualified host name in the URL.

    Figure 4-1 Rule Author Repository Connect Page

    Rule Author Repository Connect Page
    Description of "Figure 4-1 Rule Author Repository Connect Page"

    See Section B.1, "Working with a WebDAV Repository" for information about how to setup a WebDAV repository.

  5. If you have a proxy server between the server on which Rule Author is running and the WebDAV server, specify values in the Proxy User Name, and Proxy Password fields (as required for the Proxy server).

  6. Click Connect. After you connect, Rule Author displays a confirmation message.


Note:

For file repositories, only one user may edit the repository at any given time, regardless of the number of dictionaries stored in the repository. For WebDAV repositories, a single user may edit multiple dictionaries simultaneously.

4.3.2 Creating a Rule Author Dictionary

A dictionary is the top-level container and the starting point for working with Rule Author. A dictionary usually corresponds to the rules portion of an application.

To create a dictionary, do the following:

  1. Connect to a repository from the Repository tab.

  2. Click the Create secondary tab.

  3. Enter the dictionary name in the New Dictionary Name field. For this example, enter CarRentalxml.

  4. Click Create. After you click Create, Rule Author shows a status message (see Figure 4-2).

    Figure 4-2 Rule Author Create Dictionary (XML)

    Rule Author Create Dictionary (XML)
    Description of "Figure 4-2 Rule Author Create Dictionary (XML)"

4.3.3 Saving a Rule Author Dictionary with a Version

To save to a different dictionary name or specify a version for the current dictionary, use the Save As area as follows:

  1. Click the Repository tab.

  2. Click the Save As secondary tab.

  3. Enter a dictionary name in the Dictionary field, for example, CarRentalxml.

  4. To specify a version that is associated with the dictionary, enter text in the Version field, for example, HowToxml.

  5. Click Save As. After clicking Save As, Rule Author shows a confirmation message (see Figure 4-3).

    Figure 4-3 Rule Author Save Dictionary (XML)

    Rule Author Save Dictionary (XML)
    Description of "Figure 4-3 Rule Author Save Dictionary (XML)"

4.3.4 Saving a Rule Author Dictionary

To prevent data loss, you should periodically save the dictionary. To save a dictionary, do one of the following:

  • Click the Repository tab, then click the Save secondary tab.

  • Click the Save Dictionary link at the top of the page.

After performing either of the preceding actions, click Save on the Save Dictionary page. After clicking Save, you should see a confirmation message in the status area. For example:

Dictionary 'CarRentalxml(HowToxml)' has been saved


See Also:

"Rule Author Session Timeout" for details on configuring the Rule Author session timeout and for details on how Rule Author automatically saves the current work to a dictionary version when a timeout occurs

4.4 Defining a Data Model for the XML Car Rental Sample

Before working with rules you must define a data model. A data model contains business data definitions for facts or data objects used in rules, including: Java class fact types, XML fact types, and RL Language fact types. In this section, you work with a data model that includes XML fact types.

This section covers the following topics:

4.4.1 Using XML Schema as Facts in the XML Car Rental Sample

The XML sample includes the carrental.xsd file in the $HowToDir/data directory. This file specifies the schema for the XML car rental sample that uses XML documents to assert facts. The access the schema definition, replace $HowToDir with the directory where you installed the XML How-To.

4.4.2 Adding XML Facts for the Car Rental Sample (XML Schema Processing)

Before you can use XML elements in a data model, Rule Author must generate the JAXB classes representing the XML elements. This step generates the JAXB classes and makes the generated classes and packages associated with the XML schema visible to Rule Author.

To use Rule Author to prepare the sample XML car rental schema, do the following:

  1. Go to Step 2 if you just created the CarRentalxml dictionary. Click the Repository tab and load the CarRentalxml dictionary.

  2. Click the Definitions tab. The navigation tree shows the Definitions folder that contains the available definitions.

  3. The Definitions folder in the tree contains the Facts folder, which includes the available fact types: JavaFact, XMLFact, and RLFact.

    Click XMLFact to view the XMLFact Summary page (see Figure 4-4).

    Figure 4-4 Rule Author Definitions XMLFact Summary Page

    Rule Author Definitions XML Fact Summary Page
    Description of "Figure 4-4 Rule Author Definitions XMLFact Summary Page"

  4. Click Create. This shows the XML Schema Selector page.

  5. On the XML Schema Selector page, in the XML Schema field, enter either the path or HTTP URL to the schema. For example:

    • $HowToDir/data/carrental.xsd, where $HowToDir is the directory where you installed the XML How-To.

    • http://www.myCompany.com/xsd/product.xsd


    Note:

    If you choose to access the schema with a URL, and a proxy server is involved, then you must set the following system properties:
    proxyHost = $YourProxyHost
    proxyPort = $YourProxyPort
    proxySet = true
    
    

    For example:

    -DproxyHost=www-proxy.myCompany.com -DproxyPort=80 -DproxySet=true
    
    

    For more information about setting system properties in an OC4J instance, see Oracle Containers for J2EE Configuration and Administration Guide.


  6. In the JAXB Class Directory field, enter the directory where you want Rule Author to store the JAXB-generated classes. The directory that you specify must be writable. For example, enter c:/temp/xml.

  7. Enter a value for the Target Package Name field. If you leave this field empty, the JAXB classes package name is generated from the XML target namespace of the XML schema using the default JAXB XML-to-Java mapping rule. For example, the namespace rules.oracle.com is mapped to com.oracle.rules.

    The value you enter specifies the generated classes package name. For example, use the name generated (see Figure 4-5). Although this example uses the name generated, there is nothing special about this name. This name specifies the package for the generated classes.

    Figure 4-5 Rule Author XML Schema Selection Page

    Rule Author XML Schema Selection Page
    Description of "Figure 4-5 Rule Author XML Schema Selection Page"

  8. Click Add Schema.

    This step requires a period of time for Rule Author to process the schema and compile the JAXB, so depending on the size of the schema, you may need to wait for this step to complete. When this step completes the page shows the cleared Add Schema text entry fields, and Rule Author updates the Current XML Schemas field and shows the Generated JAXB Classes area (see Figure 4-6).

    Figure 4-6 Rule Author Definitions XML Schema Selector After Adding XML Schema

    Rule Author Definitions XML Schema Selector
    Description of "Figure 4-6 Rule Author Definitions XML Schema Selector After Adding XML Schema"


Note:

JAXB sometimes maps XML construct names to different Java identifier names. For example, in JAXB-generated classes, the XML name my-element-name becomes myElementName. Rule Author presents XML construct names so that you do not have to understand the JAXB-generated XML-to-Java name mapping.

4.4.3 Importing XML Schema Elements to a Data Model

This step brings the JAXB-generated classes representing the XML schema elements into the data model (from the sample schema carrental.xsd). Select the XML elements to import into the data model using the XML Schema Selector page from the Definitions tab.

To add DriverType from the schema to the data model, do the following:

  1. Click the Definitions tab to view the Definitions page.

  2. Click the XMLFact folder in the navigation tree.

  3. Click Create on the XMLFact Summary page. This shows the XML Schema Selector page.

  4. In the Generated JAXB Classes box on the XML Schema Selector page, expand the navigation tree until you see DriverType.

  5. Select the generated folder check box.

  6. Click Import.

    Rule Author shows a confirmation message: "1 class or package has been imported".

  7. Expand the Generated node in the Generated JAXB Classes area to see the imported classes (see Figure 4-16).


    Note:

    After an element is imported, the element is shown in bold.

    Figure 4-7 Rule Author XML Schema Selector with Confirmation Message

    Rule Author XML Schema Selector with confirmation
    Description of "Figure 4-7 Rule Author XML Schema Selector with Confirmation Message"

Notes for adding XML schema to Rule Author:

  • In Rule Author, importing an XML fact means the same thing as a Java import statement. That is, the JAXB classes and their methods become visible to Rule Author. Rule Author does not copy the classes into the data model or into the dictionary.

  • The Classes navigation tree is rendered on demand (to improve performance). Thus, a child node is rendered only if its parent node is expanded. It is a good practice to keep only the nodes of interest expanded.

  • On Windows systems, you can use a backslash (\) or a slash (/) as a path separator. Rule Author accepts either path separator.

  • A corresponding XML construct name is displayed next to each Java class so that you know where the Java class is generated from (using the XML schema names). To import the whole package into the data model, check the package name and click Import.

  • Do not use RL Language reserved words in Java package names. For more information, see Section D.8, "Using RL Reserved Words as Part of a Java Package Name"

  • Oracle Business Rules binds an XML schema to Java classes using the JAXB binding. In most cases, the default bindings generated by the Oracle JAXB binding compiler should be sufficient to meet your needs. There are cases, however, when you may want to modify the default bindings. For example:

    • In cases where the default binding generates a name collision.

    • In cases where the default binding generates invalid Java identifiers (it is possible to generate invalid Java identifiers from non-English tag names).


See Also:

Java Architecture for XML Binding (JAXB) Specification for details on using custom binding declarations

http://java.sun.com/xml/downloads/jaxb.html


4.4.4 Viewing XML Facts in a Data Model

To view the XML facts in a data model, including any JAXB-generated classes or packages that you import, do the following:

  1. Click the Definitions tab to view the Definitions page.

  2. In the navigation tree, expand the Facts folder and click the XMLFact node to display the XMLFact Summary page.

    For the XML car rental sample, this shows the XML fact table that includes the imported classes DriverType, RepositoryType, Repository, and ObjectFactory.

  3. Click the edit icon to view the XML Fact Properties and Methods table.

    Description of rapencil.gif follows
    Description of the illustration rapencil.gif


Note:

Importing a Java class does not cause all of its superclasses and classes associated through fields and methods to be imported into the data model. In order to access these correctly, they must be explicitly imported into the data model.


See Also:

See "Specifying Visibility and Object Chaining for Rule Author Lists" for details on the Visible and Expand fields in the XML Fact Properties and Methods table

4.4.5 Saving the Current State of XML Fact Definitions

While you are working on a data model from the Definitions tab and when you complete your work, you should save the dictionary.

To save the dictionary do the following:

  1. Click the Save Dictionary link at the top of the page.

  2. Click Save on the Save Dictionary page.

4.5 Defining the Business Vocabulary for the XML Car Rental Sample

The business vocabulary allows business analysts to create rules using familiar names rather than using an XML name or a Java package name, class name, method name, or member variable name. Rule Author provides an alias feature to allow you to refer to business objects, or facts, in rules using a vocabulary that is intended for business people. In this step, you only need to define the business vocabulary for the business objects that you expect to use in rules. In addition, you can use the Rule Author Visible box to specify the properties and methods that appear in Rule Author lists when you create rules from the Rulesets tab.

This section covers the following topics:

4.5.1 Specifying the Business Vocabulary for XML Fact Definitions

To specify the business vocabulary for XML fact definitions, do the following:

  1. Click the Definitions tab to view the Definitions page.

  2. In the navigation tree, expand the Fact folder and click the XMLFact node to display the XMLFact Summary page. For the XML car rental sample, this shows a table that includes the class generated.DriverType (if you specify a package name other than generated, then the package name is different than generated).

  3. Click the edit icon for DriverType. This shows the XMLFact page.

  4. At the top of the XMLFact page, in the Alias field, enter DriverData.

  5. For the age entry in the Properties table, specify the desired alias. For example, enter DriverAge in the Alias field.

  6. For the name entry in the Properties table, specify the desired alias. For example, in the Alias field, enter DriverName.

  7. Click OK or Apply.

  8. Save the dictionary.


Note:

Be sure to click OK or Apply after making changes. Otherwise, Rule Author does not save your changes.

Notes for specifying the business vocabulary for XML fact definitions:

  • The XMLFact page includes the XML Name and Generated From fields that show the Java class was generated from an XML schema.

    For example, //complexType[@name='driverType'] XML Name shows that the class is generated from an XML complex type named driverType. The Generated From field shows the name of the XML schema that generated the JAXB classes for the XML fact.

  • On the XMLFact page, you can specify that Rule Author shows methods or properties one level above a specified method or property, in superclass chain, by selecting the Expand box for the method or property on the XMLFact page. The Expand box is shown in the Expand field of the Properties and Methods area. The check box is only shown for methods or properties that include a superclass (Rule Author does not show the Expand box for primitive types).

  • On the XMLFact page you can specify that properties or classes are not visible in Rule Author lists. Deselect the Visible check box to specify that an object is not visible in Rule Author lists (by default objects are visible in lists).

  • Make sure the Support XPath Assertion box is checked for all XML fact types. For more information, see Section D.10, "XML Facts not Asserted at Runtime".

4.5.2 Specifying the Business Vocabulary for Functions

To specify the business vocabulary for an RL Language function, do the following:

  1. Click the Definitions tab to view the Definitions page.

  2. In the navigation tree, click RLFunction in the Definitions folder to display the RLFunction Summary page. For the XML car rental sample, this shows a table that includes the functions DM.assertXPath and DM.println.

  3. For the DM.println function, click the edit icon in the Edit field to view details.

  4. In the Alias field, under the Name field, enter an alias. For example, enter PrintOutput in the Alias field.


    Note:

    There is also an Alias field in the Function Arguments table. For this example do not change the function arguments alias.

  5. Click OK or Apply.

  6. Save the dictionary.

4.5.3 Specifying the Visibility for Properties and Methods for XML Facts

To specify whether properties or methods are visible in Rule Author lists, do the following:

  1. Click the Definitions tab to view the Definitions page.

  2. In the navigation tree, click the XMLFact node to display the XMLFact Summary page.

  3. Click the edit icon to view the XML fact Properties and Methods for DriverType (in the table this entry has the value DriverData in the Alias column). This shows the XMLFact page.

  4. For each entry in the Properties table and in the Methods table, specify the desired visibility using the Visible check box. For this example, only the member variables age and name need to be visible.

  5. Click OK or Apply to save the changes.

  6. Save the dictionary.


Note:

Modifying the visibility indicators for a particular property or method may cause dependent definitions or rules to display incorrectly. If this occurs, mark any non-visible properties or methods causing the problem as visible.

4.6 Defining a Rule for the XML Car Rental Sample

In this section, you define a rule for the XML car rental sample.

This section covers the following topics:

4.6.1 Creating a Rule Set for the XML Car Rental Sample

Before you can create a rule you must create a rule set. A rule set is a container for rules.

To create a rule set, do the following:

  1. Click the Rulesets tab.

  2. Click the RuleSet node in the navigation tree.

  3. On the Ruleset Summary page, click Create. This displays the Ruleset page.

  4. Enter a name in the Name field. For example, enter vehicleRent.

  5. Optionally enter text in the Description field. For example, enter vehicle rent rule set.

  6. Click OK. This creates the vehicleRent rule set. After you create the rule set, the tree shows the new entry, as shown in Figure 4-8.

  7. Save the dictionary.

    Figure 4-8 Rule Author RuleSet Summary Page

    Rule Author RuleSet Summary Page
    Description of "Figure 4-8 Rule Author RuleSet Summary Page"

4.6.2 Creating a Rule for the XML Car Rental Sample

After creating a rule set, you can create rules within the rule set. In this section, you create the UnderAge rule. The UnderAge rule tests the following:

If the age of the driver is younger than 21, then decline to rent

The UnderAge rule contains a single pattern for Rules Engine to match, and the rule includes a test that is applied to the pattern.

The following actions are associated with the UnderAge rule:

  • Print "Rental declined", the name of the driver matched, and the message, "Under Age, age is: ", and the age of the driver.

  • Retract the matched driver fact from the rule session. You might want to retract a fact for a number of reasons, including: If you are done with the fact, and you want to remove it from the Rules Engine or if the action associated with the rule changes the state, so that the fact must be retracted to represent the current state of the Rules Engine

4.6.2.1 Adding the UnderAge Rule for the XML Car Rental Sample

To use Rule Author to add the UnderAge rule, do the following:

  1. Click the Rulesets tab. The navigation pane displays the RuleSet folder that contains the vehicleRent rule set that you created in Section 4.6.1.

  2. Click the vehicleRent node in the navigation tree. This displays the Ruleset page, with a table listing rules (see Figure 4-9).


    Note:

    If there are no rules, the Rules table is empty.

    Figure 4-9 Rule Author RuleSet Page Showing the Create Button

    Rule Author RuleSet Page Showing the Create Button
    Description of "Figure 4-9 Rule Author RuleSet Page Showing the Create Button"

  3. Click Create. This displays the Rule page.

  4. On the Rule page, in the Name field, enter UnderAge .

  5. On the Rule page, in the Priority field, enter 0.


    Note:

    The Priority field determines which rule to act upon, and in what order, if more than one rule applies. Often in applications that use rules, the rules in a rule set are applied in any order until a decision is reached, and setting a priority is not required.

  6. Optionally enter a description in the Description field (see Figure 4-10).

    Figure 4-10 Rule Author Rule Page

    Rule Author Rule Page
    Description of "Figure 4-10 Rule Author Rule Page"

4.6.2.2 Adding a Pattern to the UnderAge Rule (XML)

When Rules Engine runs, it uses the rules to check the available facts for matching patterns. To add a pattern for the UnderAge rule, do the following:

  1. On the Rule page, click New Pattern in the If box. This displays the Pattern Definition page.

    The Pattern Definition page contains two areas: Choose Pattern and Define Test for Pattern (see Figure 4-11).


    Note:

    If the Pattern Definition page does not appear, you may have popup blocking enabled on your browser. Popup blocking must be disabled in order to use Rule Author.

    Figure 4-11 Rule Author Pattern Definition Page

    Rule Author Pattern Definition Page
    Description of "Figure 4-11 Rule Author Pattern Definition Page"

  2. Under Choose Pattern, in the first box select the first entry, which is blank.

    This box specifies that the rule should fire each time there is a match (for all matching drivers). One alternative value, There is at least one case, selects one firing of the rule if there is at least one match (one such driver). The alternate value, There is no case, specifies the rule fires once if there are no such matches (no matching drivers).

  3. The next text area under Choose Pattern lets you enter a temporary name for the matched fact.

    Enter driver in this field (this defines the "pattern bind variable name").

    This field lets you test multiple instances of the same type in a single rule. For example, this lets you compare a driver with other drivers, using the specified name, in a comparison such as driver1.age > driver2.age.

  4. The third box contains the text <make a choice>. This box shows the available fact types. In this box, select DriverData.

  5. Click OK to save the pattern definition and close the Pattern Definition page.

  6. On the Rule page, click OK or Apply to save the rule.


    Note:

    Changes made to the pattern are not added to the rule until you click OK or Apply on the Rule page. If you navigate to a different rule set or select a different tab before you click OK or Apply, Rule Author discards your pattern definition changes.

  7. Save the dictionary.

Without any tests defined on the pattern, the action that you define would apply to all drivers. To define tests for patterns, continue, as shown in Section 4.6.2.3.

4.6.2.3 Defining Tests for Patterns with the Under Age Rule (XML)

To add a test for a pattern, do the following:

  1. From the Rulesets tab, in the navigation tree click the rule where you want to add a test. For this example, click the node for the UnderAge rule.

  2. In the If table on the rule page, select the pencil icon to display the Pattern Definition page for this rule.

  3. On the Pattern Definition page, select the Standard Test button, then click Create (see Figure 4-12). For more information, see Section 3.8.1, "Using the Advanced Test Expression Option".

    Figure 4-12 Rule Author Rule Pattern Definition Page with New Test Fields

    Rule Author Pattern Definition Page with fields
    Description of "Figure 4-12 Rule Author Rule Pattern Definition Page with New Test Fields"

  4. In the Operand column, from the Field box, select driver.DriverAge.

  5. In the Operator column, select < (less than).

  6. In the next Operand column, in the Value box enter 21. Do not enter a value in the Field box.

  7. Next to each Value and Field box is a list containing the values Fixed and Any (see Figure 4-13).

    Select Any as the constraint for the Value field.

    These values are called constraints. Use constraint values to enable or disable customization. Use the value Fixed to make the field read-only, which specifies that no customization is allowed for this value. Select the value Any to specify that Rule Author should allow changes to the value. Setting a value of Any allows for rule customization (which supports modifications by nontechnical users). You can also define constraints that allow you to limit the allowed values.

    Figure 4-13 Rule Author Pattern Definition Page with Values for the UnderAge Rule

    Rule Author Pattern Definition Page with values
    Description of "Figure 4-13 Rule Author Pattern Definition Page with Values for the UnderAge Rule"

  8. Click OK to save your changes and close the Pattern Definition page.

  9. On the Rule page, click OK or Apply.


    Note:

    Changes made to the pattern are not added to the rule until you click OK or Apply on the Rule page. If you do not click OK or Apply, Rule Author does not save your work on the rule.

  10. Save the dictionary.

Note the following when you define a test for a pattern:

  • In Standard Test expressions, the tests only evaluate to true when all of the tests that you define match. Additionally, in standard tests, no grouping is allowed, and functions with parameters are not allowed. However, with standard tests you can define constraints for customization.

  • In Advanced Test expressions, the tests do not have the restrictions of standard tests, but they do not allow the use of constraints. Advanced test expressions are not directly saved using RL Language because Rule Author incorporates aliases in the expressions; aliases are not supported in RL Language (Rule Author maps aliases to variable names).

4.6.2.4 Adding Actions for the UnderAge Rule (XML)

Actions are associated with pattern matches. At runtime, when the "If" portion of a rule matches, Rules Engine executes the "Then" portion to run the action or actions associated with the rule.

In this section, you add two actions for the UnderAge rule. The first action prints the result. The second action retracts the driver fact from the Rules Engine. You might want to retract a fact for a number of reasons, including:

  • If you are done with the fact, and you want to remove it from Rules Engine.

  • The action associated with the rule changes the state, so that the fact must be retracted to represent the current state of Rules Engine.

To add the action that prints the result for a match of the UnderAge rule, do the following:

  1. Click the Rulesets tab.

  2. In the tree, under the vehicleRent folder, click the node for the UnderAge rule.

  3. On the Rule page in the Then box, Click New Action. This displays the Add Action page (see Figure 4-14).

    Figure 4-14 Rule Author Add Action Page

    Rule Author Add Action Page
    Description of "Figure 4-14 Rule Author Add Action Page"

  4. From the Action Type box, select the Call item. This shows the Action Parameters box.

  5. From the Function box, choose PrintOutput (if you did not define an alias for println, then this is DM.println). This shows the Function Arguments box.

  6. In the Argument Value field, enter the argument value (see Figure 4-15):

    "Rental declined" + driver.DriverName + " Under age,age is:" + driver.DriverAge 
    

    Note 1:

    Rule Author uses a Java-like syntax for expressions. RL Language defines the complete expression syntax.


    Note 2:

    You can also select the edit icon in the Wizard field to use the Wizard to enter the expression. This provides you with more space to write expressions. This also provides an easier and more accurate way to enter variables, because the Wizard presents a list showing the available variables.

    Figure 4-15 Rule Author Add Action Page for the UnderAge Rule

    Rule Author Add Action Page
    Description of "Figure 4-15 Rule Author Add Action Page for the UnderAge Rule"

  7. Click OK to save your changes and close the Add Action page.

  8. On the Rule page, click OK or Apply.

  9. Save the dictionary to save your work.

Next, add the retract action for the UnderAge rule. Perform the following steps to add this second action for the rule:

  1. Click the Rulesets tab.

  2. Under the vehicleRent folder, click the node for the UnderAge rule.

  3. On the Rule page, from the Then box, click New Action. This displays the Add Action page.

  4. From the Action Type box, select Retract. This shows the Action Parameters box.

  5. From the Fact Instance box, select driver. The pattern name (driver) when used in the action, refers to a single instance that was matched by the pattern.

  6. Click OK to save your changes and close the Add Action page.

  7. On the Rule page, click Ok or Apply to save the changes (see Figure 4-16).

  8. Save the dictionary.

    Figure 4-16 Rule Author Under Age Rule with Pattern and Actions

    Rule Author Under Age Rule with Pattern and Actions
    Description of "Figure 4-16 Rule Author Under Age Rule with Pattern and Actions"


Note:

When you add actions to rules, you can only add new actions sequentially. If an action depends on the results of a previous action, then the order in which you add the actions is significant.

4.7 Customizing Rules for the XML Car Rental Sample

The Rule Author Customization tab is designed for business users. Rule developers use the Allowed Values field on the Pattern Definition page, which is available from the Rulesets tab, to specify if customization is allowed. When customization is allowed, you can specify a range of values for the customizable value. Then, business users can change values using the Customization tab.

In this example, the UnderAge rule can be modified on the Customization tab to change the age of an underage driver (for this sample we do not limit values, and specify that any value is valid).

To change the UnderAge rule, use the Customization tab as follows:

  1. Click the Customization tab. The navigation pane displays the vehicleRent folder with node for the UnderAge rule followed by an asterisk (*), which indicates that the rule is customizable.

  2. Click the node for the UnderAge rule (see Figure 4-17).

    Figure 4-17 Rule Author Rule Customization Page for the UnderAge Rule

    Rule Author Under Age Rule Customization
    Description of "Figure 4-17 Rule Author Rule Customization Page for the UnderAge Rule"

  3. On the Rule Customization page, the Customize Patterns box contains an editable text entry field for the test driver.DriverAge < 21.

    Enter 19 in this field (change the value from 21 to 19).

  4. Click Apply.

  5. Save the dictionary.

After you save the dictionary, you are done creating the data model and the rules for the XML car rental sample.

4.8 Creating a Java Application with a Rule Session Using XML Facts

After you create and save a Rule Author dictionary that contains a data model and a rule set with rules, you can rule-enable an existing Java application or create a new rule-enabled Java application. This section shows you the steps for creating a rule- enabled application.

This section covers the following topics:

For the complete code for this sample application, see TestXML.java in the $HowToDir/src/carrental directory, where $HowToDir is the directory where you installed the XML How-To.


Note 1:

If you have completed the Java car rental example from Chapter 2, the differences in this example are that you must create a JAXB context, and that you must use the assertXPath function to add facts to a rule session.


Note 2:

The instructions in the preceding sections of this chapter enabled you to create and save a WebDAV repository and dictionary named CarRentalxml. The car rental example supplied in the How-To sample code uses a file repository with a dictionary also named CarRentalxml. The dictionary contents in the WebDAV repository you created in this chapter and the file repository in the How-To sample are identical.

The How-To sample code contains code for both WebDAV and file repositories, but only the file repository is described in detail. The How-To sample uses a file repository for portability, but this sample can be modified to use the WebDAV repository you created in the proceeding sections.


4.8.1 Importing the Rules SDK and Rules RL Classes

The first step when you write a rule-enabled program is to import certain required classes. Example 4-1 shows the imports from the TestXML.java application for the XML car rental sample.

Example 4-1 Required Imports for XML Car Rental Sample with Rules SDK

package carrental;

import java.io.File;
import java.util.List;
import java.util.ArrayList;
import java.util.Properties;

import javax.xml.bind.*;

import oracle.rules.sdk.ruleset.RuleSet;
import oracle.rules.sdk.repository.RuleRepository;
import oracle.rules.sdk.repository.RepositoryManager;
import oracle.rules.sdk.repository.RepositoryType;
import oracle.rules.sdk.repository.RepositoryContext;
import oracle.rules.sdk.dictionary.RuleDictionary;
import oracle.rules.sdk.exception.RepositoryException;
import oracle.rules.sdk.store.jar.Keys;

import oracle.rules.rl.RuleSession;

4.8.2 Creating a JAXB Context and Unmarshalling the XML Document

Using the JAXB-generated classes, you first must specify a JAXB context and then unmarshall an XML document that conforms to the schema. Example 4-2 shows this code from TestXML.java.

Example 4-2 Unmarshalling an XML Document

JAXBContext jc = JAXBContext.newInstance("generated");
Unmarshaller um = jc.createUnmarshaller();
String fs = System.getProperty("file.separator");
String xmlpath = "data" + fs + "carrental.xml" ;
Object root = um.unmarshal(new File(xmlpath));

4.8.3 Initialize the Repository with Rules SDK

When building a rule-enabled Java application, do the following to access a dictionary and specify a rule set (see Example 4-3):

  1. Create a String that contains the path to the repository.

  2. Use a Rules SDK RuleType object to hold the repository that you obtain from the RepositoryManager.getRegisteredRepositoryType method.

  3. Create a repository instance using the repository manager method createRuleRepositoryInstance.

  4. Define a RepositoryContext and set appropriate properties. For a file repository, this step specifies the path to the repository, as shown with the repoPath parameter.

  5. Use the init method in the RuleRepository object repo to initialize the repository instance.

Example 4-3 Loading a Dictionary with Rules SDK (XML)

String repoPath = "dict" + fs + "CarxmlRepository";
RepositoryType jarType =
   RepositoryManager.getRegisteredRepositoryType(  Keys.CONNECTION );
RuleRepository repo = RepositoryManager.createRuleRepositoryInstance( jarType );
RepositoryContext jarCtx = new RepositoryContext();
jarCtx.setProperty( oracle.rules.sdk.store.jar.Keys.PATH, repoPath );
repo.init( jarCtx );

To load a WebDAV repository instead of a file repository as shown in Example 4-3, you should use getWebDAVRepository. An example of this is shown in TestXML.java in the $HowToDir/src/carrental directory.

4.8.4 Loading A Dictionary with Rules SDK

When you build a rule-enabled Java application you must load a dictionary, with a specified version. Use a RuleDictionary object to load a dictionary, as shown in Example 4-4, which loads the CarRental dictionary, with the HowTo version, into the object named dict. The CarRental dictionary must be available in the repository (the CarRental dictionary with the version name HowTo was created earlier using Rule Author).

Example 4-4 Loading a Dictionary With Rules SDK

RuleDictionary dict = repo.loadDictionary( "CarRentalxml", "HowToxml" );

4.8.5 Loading a RuleSet and Generating RL Language for a Data Model and Rule Set

After loading a dictionary, you can use Rules SDK to generate an RL Language program. This step is required, because a dictionary stores a data model and rule sets using an intermediate XML format. The RuleDictionary object provides methods to access a data model and a rule set and perform the mapping from the intermediate XML format. This mapping produces the RL Language data program.

When you generate rules using Rule Author, each rule set specifies two components, a data model, which is global and applies to all the rule sets in a dictionary, and the set of rules associated with a rule set.

Example 4-5 shows the code that generates the RL Language code for a rule set and for the associated data model.

Example 4-5 Generating Oracle Business Rules RL Language

String rsname = "vehicleRent";String dmrl = dict.dataModelRL();String rsrl = dict.ruleSetRL( rsname );

4.8.6 Initializing and Executing a Rule Session

After you generate an RL Language program that include rules and a data model, you are ready to work with a rule session. A rule session initializes Rules Engine and maintains the state of Rules Engine across a number of rule executions.

Example 4-6 shows the code that creates a RuleSession object and executes an RL Language program.

The executeRuleset() method tells Rules Engine to interpret the specified RL Language program.


Note:

The order of the executeRuleset() calls is important. You must execute the data model RL Language program before the rule set RL Language program. The data model contains global information that is required when the associated rule set executes.

Example 4-6 Initializing and Executing a Rule Session with Rules SDK (XML)

RuleSession session = new RuleSession();
session.executeRuleset( dmrl );
session.executeRuleset( rsrl );

session.callFunction( "reset" );        
session.callFunction( "clearRulesetStack"  );
session.callFunctionWithArgument( "pushRuleset", rsname );

After the data model and the rule set are loaded, the rule session is ready to run the rule set against the facts that you assert for the rule session.

4.8.7 Asserting XML Data from Within a Rule Session

Before running a rule session, you first must unmarshall the XML document containing the XML data and then assert the facts from the XML document. Section 4.8.2 shows you how to unmarshall the XML document.

To assert facts from an XML document, use the session.callFunctionWithArgument() method with the assertXPath function as an argument.

Example 4-7 shows sample code that uses assertXPath to assert XML facts into a rule session.

The callFunctionWithArgumentList method requires a function name argument and a List argument. The List argument argList includes the following three arguments:

  1. The first argument for assertXPath is the JAXB-generated package name, for this example, generated.

  2. The second argument for assertXPath is the root object for the unmarshalled XML document. For this example, the unmarshalled object reference is the root object.

  3. The third argument for assertXPath is the XPath expression to assert. For this example, the "//*" asserts the entire XML tree into the rule session named session.

Example 4-7 Asserting an XML Document

List argList = new ArrayList(3);
argList.add( "generated" );
argList.add( root );
argList.add( "//*" ); 
session.callFunctionWithArgumentList( "assertXPath", argList );

4.8.8 Using the Run Function with a Rule Session

Example 4-8 shows the code that runs a rule session.

Example 4-8 Running an Oracle Rules Engine Session

session.callFunction( "run");

4.9 Running the XML Car Rental Sample Using the Test Program

The $HowToDir/lib directory includes TestXML.jar, a ready-to-run Oracle Business Rules Java application that uses the CarRentalxml dictionary. If you change the dictionary name and you must modify TestXML.java, the source is available in the directory $HowToDir/src. The Readme.txt file in this directory includes instructions for setting the environment variables required to run the test program, where $HowToDir is the directory where you installed the XML How-To.

Example 4-9 shows output from running TestXML.

Example 4-9 Sample Run of Car Rental Program (XML)

java carrental.TestXMLRental declined Qun Under age, age is: 15

Note that not all facts produce output or fire a rule. The example shows output only for the asserted fact that matches the UnderAge rule.