Skip Headers

Oracle® Business Rules User's Guide 10g Release 3 (10.1.3) B15986-01 |
| Home | Solution Area | Contents | Index

Previous | Next |

# 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 XML car rental How-To, driver data, supplied in an XML document specifies driver information, and the business rules determine if a rental company service representative should decline to rent a vehicle due to driver age restrictions (according to rental company business rules).

This chapter covers the following topics:

- Overview of Using XML Documents and Schemas with Rule Author

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

- Defining a Data Model for the XML Car Rental Sample

- Defining Business Vocabulary for the XML Car Rental Sample

- Defining a Rule for the XML Car Rental Sample

- Customizing Rules for the XML Car Rental Sample

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

- Running the XML Car Rental Sample Using the Test Program

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

Starting with an XML schema, using XML documents with Rule Author involves the following steps:

1. XML schema processing: Rule Author generates Java classes from 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. Using Rule Author you import XML elements into the data model in a dictionary.

3. Using Rule Author you define rules that reason on XML elements from an XML document. The process of writing rules for XML documents is very similar to writing rules using Java objects.

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

Note 1: JAXB sometimes maps XML construct names to different Java identifier names. For example, using JAXB, 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.

Note 2: If you want to use a JAXB binding compiler that is different from the Rule Author supplied implementation, you can manually perform the XML schema processing using your JAXB binding compiler and then use Java facts to import the generated Java packages and classes.

See Also: `http://java.sun.com/webservices/jaxb` for more information on JAXB.

## 4.2 Creating and Saving a Dictionary for the XML Car Rental Sample

To work with Rule Author you need to start with a dictionary. Rule Author stores rules and their associated definitions in a dictionary. To create or save a dictionary, you need to 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 car rental How-To.

The example in this chapter saves the dictionary to 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 install the How-To containing the XML car rental sample.

### 4.2.1 Connecting to a Rule Author Repository

Using Oracle Business Rules, a dictionary stores rules and the data model associated with the rules. You create and save dictionaries in a repository.

Note: Regardless of whether you choose to use a WebDAV or file repository, the repository must exist before you can connect to it. Rule Author does not create the repository for you. 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. Select the `WebDAV` repository type in the Repository Type field.

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

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

   See Section B.1, "Working with a WebDAV Repository" for information on 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 the name and port number of the proxy server.

6. Click Connect.

   If you connect successfully, you receive a confirmation message.

### 4.2.2 Creating a Rule Author Dictionary

A Rule Author 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)

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

### 4.2.3 Saving a Rule Author Dictionary with a Version

If you want 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. If you want 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, you should see a confirmation message in the status area (see Figure 4-3).

   Figure 4-3 Rule Author Save Dictionary (XML)

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

Note: Rule Author does not allow you to use Save As to overwrite a dictionary with the same name and version. If you want to overwrite a dictionary with the same name and version, do one of the following: Click Save. Delete the existing dictionary, then click the Save As.

### 4.2.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 'CarRental(HowTo)' has been saved

Note: You should save the dictionary periodically as you work since Rule Author sessions time out after a period of inactivity.

See Also: "Rule Author Session Timeout" for details on configuring the Rule Author session timeout.

## 4.3 Defining a Data Model for the XML Car Rental Sample

Before working with rules you need to 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:

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

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

- Importing XML Schema Elements to a Data Model

- Viewing XML Facts in a Data Model

- Saving the Current State of XML Fact Definitions

See Also: "Adding Java Classes and Packages to Rule Author"

### 4.3.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.

Where $HowToDir is the directory where you installed the XML car rental How-To.

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

Before you can use XML elements in a data model, Rule Author needs to 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 that 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 XML Fact Summary Page

   Description of "Figure 4-4 Rule Author Definitions XML Fact 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`

   If you choose to access the schema with a URL, 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 on 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.

   Note: the directory that you specify must be writable.

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 schema's target namespace 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, `generated` (for this example, we use the name generated, there is nothing special about the name generated. This value specifies the name of the package, directory, where the generated classes are placed). See Figure 4-5.

   Figure 4-5 Rule Author XML Schema Selection Page

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

8. Click Add Schema. This step requires some processing to compile the JAXB, so depending on the size of the Schema, you may need to wait for a period of time for this step to complete.

   When this completes the page shows 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

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

See Also: "Creating and Saving a Dictionary for the XML Car Rental Sample"

### 4.3.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 Class Selector page from the Definitions tab.

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

1. Name collision

2. Invalid Java identifiers mapped from non-English tag names

Please refer to Oracle JAXB documentation for more details about customizing the default XML-to-Java mapping.

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" (see Figure 4-7).

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

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

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

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

Notes for Adding XML Schema to Rule Author:

- 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 "`\`" or a "/" 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). If you want to import the whole package into the data model, check the package name and click Import.

- Using Rule Author, importing an XMLFact 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.

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

### 4.3.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. Expand the Facts folder and click the XMLFact node in the navigation tree to display the XMLFact Summary page.

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

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

   Description of the illustration rapencil.gif

Note: Importing a Java class does not cause all of its super classes 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 Drop Down Lists" for details on the Visible and Expand fields in the XML Fact Properties and Methods table.

### 4.3.5 Saving the Current State of XML Fact Definitions

While working on a data model from the Definitions tab and when you complete your work, it is important to save the dictionary. You can save the dictionary in two ways:

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

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

See Also: "Saving a Rule Author Dictionary"

## 4.4 Defining 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. You use the Rule Author aliases feature to specify the business vocabulary. 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 show up in Rule Author lists when you create rules from the RuleSets tab.

This section covers the following topics:

- Specifying the Business Vocabulary for XML Fact Definitions

- Specifying the Business Vocabulary for Functions

### 4.4.1 Specifying the Business Vocabulary for XML Fact Definitions

To specify the business vocabulary for XMLFact definitions, do the following:

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

2. Expand the Facts folder and click the XMLFact node in the navigation tree to display the XML Fact 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 XML fact page.

4. At the top of the XML fact 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, enter `DriverName` in the Alias field.

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:

- On the XML fact 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 XML Fact page. The Expand box is shown in the Expand field of the Properties and Methods area. The checkbox is only shown for methods or properties that include a superclass (Rule Author does not show the Expand box for primitive types).

- On the XML fact page you can specify that properties or classes are not visible in Rule Author list boxes. Deselect the Visible checkbox to specify that an object is not visible in Rule Author list boxes (by default objects are visible).

- The XML Fact 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.

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

### 4.4.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. Click RLFunction in the Definitions folder in the navigation tree 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 we are not changing the function arguments alias.

5. Click OK or Apply.

6. Save the dictionary.

## 4.5 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:

- Creating a Rule Set for the XML Car Rental Sample

- Creating a Rule for the XML Car Rental Sample

### 4.5.1 Creating a Rule Set for the XML Car Rental Sample

Before you can create a rule you need to 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

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

### 4.5.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 driver's age is younger than 21, then decline to rent

The UnderAge rule contains a single pattern for the 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 driver's age.

- Retract the matched driver fact from the rule session.

#### 4.5.2.1 Adding the Under Age 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.5.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

   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 enter `UnderAge` in the Name field.

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

   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 are be applied in any order until a decision is reached, and setting a priority is not required.

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

   Figure 4-10 Rule Author Rule Page

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

#### 4.5.2.2 Adding a Pattern to the Under Age Rule (XML)

When the 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. Click New Pattern in the If box on the Rule page. This displays the Pattern Definition page.

   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.

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

   Figure 4-11 Rule Author Pattern Definition Page

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

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

4. 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`.

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

6. Click OK to save the pattern definition. This closes the Pattern Definition page.

7. Click OK 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.

8. 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.5.2.3.

See Also: "Adding Actions for the Under Age Rule (XML)"

#### 4.5.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 UnderAge rule.

2. In the If table on the rule page, select the pencil icon to bring up 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).

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

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

   Standard pattern testing is only valid for AND expressions. Additionally, no grouping is allowed, and functions with parameters are not allowed. However, the use of constraints is allowed for customization. Advanced pattern testing does not have the restrictions of standard pattern testing, but the use of constraints is not allowed. Advanced expressions are not directly RL Language because aliases are used instead of variable names.

   For more information, see Section 3.7.1, "Using the Advanced Test Expression Option".

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 the Value and Field boxes is a drop-down list containing the fixed values `Any` and `Fixed` (see Figure 4-13).

   These values are called constraints, and they are used to enable or disable customization for this field. Use the value `Fixed` to make the field read-only, which specifies that no customization is allowed for this field. 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 non-technical users). You can also define constraints that allow you to limit the allowed values.

   Select `Any` as the constraint for the Value field.

   Figure 4-13 Rule Author Pattern Definition Page with Values for Under Age Rule

   Description of "Figure 4-13 Rule Author Pattern Definition Page with Values for Under Age 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.

See Also: "Customizing Rules for the XML Car Rental Sample"

#### 4.5.2.4 Adding Actions for the Under Age Rule (XML)

Actions are associated with pattern matches. When a rule's "If" portion matches, the Rules Engine executes the "Then" portion to run the rule's action.

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 the Rules Engine.

- The action associated with the rule changes the state, so that the fact needs to be retracted to represent the current state of the 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, click the UnderAge node under the vehicleRent folder.

3. Click New Action on the Rule page in the Then box. This brings up the Add Action page (see Figure 4-14).

   Figure 4-14 Rule Author Add Action Page

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

4. Select the `Call` item from the Action Type box. This shows the Action Parameters box.

5. Choose `PrintOutput` from the Function box (if you did not define an alias for `println`, then this is `DM.println`). This shows the function arguments box.

6. Enter the argument value in the Argument Value field (see figure Figure 4-15):

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

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

   Note: You can also select the edit icon in the Wizard field to use the expression builder 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, since the expression builder presents a list showing the available variables.

   Figure 4-15 Rule Author Add Action Page for Under Age Rule

   Description of "Figure 4-15 Rule Author Add Action Page for Under Age Rule"

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

8. Click OK or Apply on the Rule page.

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. Click the UnderAge node under the vehicleRent folder.

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

4. Select `Retract` from the Action Type box. This shows the Action Parameters box.

5. Select `driver` from the Fact Instance box. The pattern name `driver,` when used in the action refers to a single instance which was matched by the pattern.

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

7. Click Apply on the Rule page to receive a confirmation message (see Figure 4-16).

8. Save the dictionary.

   Figure 4-16 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.

See Also: The Oracle Business Rules RL Language Reference Guide

## 4.6 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 Ruleset 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 may 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 under age 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 the UnderAge node followed by a "*", 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 Under Age Rule

   Description of "Figure 4-17 Rule Author Rule Customization Page for Under Age 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.

See Also: Defining Tests for Patterns with the Under Age Rule (XML)

## 4.7 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:

- Importing the Rules SDK and Rules RL Classes

- Creating a JAXB Context and Unmarshalling the XML Document

- Loading a Dictionary with Rules SDK

- Loading a Ruleset and Generating RL Language for Data Model and Rule Set

- Initializing and Executing a Rule Session

- Asserting XML Data from Within a Rule Session

- Using the Run Function with a Rule Session

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 need to create a JAXB context, and when you add facts to a rule session you use the assertXPath function.

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.7.1 Importing the Rules SDK and Rules RL Classes

The first step when writing an Oracle Business Rules 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.rl.RuleSession;

### 4.7.2 Creating a JAXB Context and Unmarshalling the XML Document

Using the JAXB generated classes either generated using Rule Author or manually, you first need to specify a JAXB context and 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.7.3 Loading a Dictionary 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. Use a Rules SDK `RuleRepository` object to access one or more dictionaries. The parameter to the `getDefaultRepository` method specifies the location of the dictionary directory.

2. Use a Rules SDK `SecurityInfo` object to specify the credentials for accessing a dictionary (the default rule storage plug-in uses file-based storage and does not require credentials).

3. Use a `RuleDictionary` object to load a particular dictionary, as shown in Example 4-3, which loads the `CarRentalxml` dictionary into the object named `dict`. The `CarRentalxml` dictionary was previously created using Rule Author.

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

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

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

If you want 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.7.4 Loading a Ruleset and Generating RL Language for Data Model and Rule Set

After loading a dictionary, you can use the Rules SDK to generate an RL Language program. This step is required since a dictionary stores a data model and rule sets using an intermediate XML format. The `RuleDictionary` 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 for all the rule sets in a dictionary, and the set of rules associated with a rule set.

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

Example 4-4 Generating Oracle Business Rules RL Language

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

### 4.7.5 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 the Rules Engine and maintains the state of the Rules Engine across a number of rule executions.

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

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

Note: The order of the `executeRuleset()` calls is important. You need to 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-5 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 and the rule session is ready to run the rule set against the facts that you assert for the rule session.

### 4.7.6 Asserting XML Data from Within a Rule Session

Before running a rule session you need to first unmarshall the XML document containing the XML data and then assert the facts from the XML document. Section 4.7.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-6 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-6 Asserting an XML Document

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

See Also: "Creating a JAXB Context and Unmarshalling the XML Document"

### 4.7.7 Using the Run Function with a Rule Session

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

Example 4-7 Running a Rules Engine Session

    session.callFunction( "run");

## 4.8 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 need to 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 Oracle Business Rules XML How-To.

Example 4-8 shows output from running `TestXML`.

Example 4-8 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.