Oracle® Business Rules User's Guide 10g (10.1.3.1.0) Part Number B28965-02 |
|
|
View PDF |
This chapter provides a tutorial introducing Oracle Business Rules Rule Author (Rule Author). This chapter shows you how to start Rule Author, create a data model, and create and save rules and shows you how to create a sample Java application that runs with the Rules Engine.
In this guide we use a car rental sample to illustrate how to work with Rule Author. In the car rental sample, driver data 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. Using this example you create one rule, the UnderAge rule (the rule is specified according to rental company business rules).
This chapter includes the following sections:
Note:
We call the sample application that we build in this chapter the Java 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-java.zip
If you are using Oracle Application Server, you must first create a user with appropriate privileges before you can start and use Rule Author. To do this:
Note:
These instructions assume that the container is configured with the JAZN XML provider. If it is not, you should refer to the appropriate security documentation for information about creating users.Using Application Server Control, go to the OC4J instance where Rule Author was deployed.
Click the Administration tab.
In the "Task Name" column, find the "Security Providers" task and click the "Go to Task" icon in the corresponding row.
Click Instance Level Security.
Click the Realms tab.
In the table in the "Results" section, click the number in the "Users" column to add a user.
Click the Create button.
In the "Name" field, enter the name you want to use to login to Rule Author (for example, ruleadmin
). Enter and confirm the password for this user. In the "Assign Roles" section, double-click or use the arrows to assign the rule-administrators
role to this user. When you are finished, click OK.
Note:
In order for Rule Author authentication to work, the Rule Author user must belong to therule-administrators
role.Restart the Rule Author application.
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. For example:
http://myhost1.mycompany.com:8888/ruleauthor/
Note:
The port number assigned to Oracle Application Server can be found in thereadme.txt
file located in the $ORACLE_HOME
/install
directory.Figure 2-1 shows the Rule Author login page. Specify the user name and password you supplied when you created the Rule Author user (Section 2.1, "Creating a Rule Author User").
Figure 2-1 Rule Author Single Sign-on Login Page
After logging in, click the Repository tab to see the Rule Author Repository Connect page (see Figure 2-2). You must connect to a repository before you can perform any operations. See Section 2.4.1, "Connecting to a Rule Author Repository" for more information.
Figure 2-2 Initial Rule Author Repository Connect Page
Each Rule Author page provides the Logout, Help and About links. You can use these links as follows:
Click Logout to go to the Logout Confirmation page. On this page, click either Logout to log out of Rule Author, or Save and Logout to save your changes and log out of Rule Author. After doing so, you must log back in to Rule Author (see Figure 2-1).
Click Help to access online help for the Rule Author.
Click About to view Rule Author version and build information (Figure 2-3). Click OK to dismiss this window.
Click the Home tab to access the Rule Author home page (Figure 2-4). The home page contains two panes: the top pane shows the tabs and the bottom pane contains content for the currently selected tab.
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 first connect to a repository that stores the dictionary. As shipped, Rule Author supports two types of repositories: WebDAV (Web Distributed Authoring and Versioning) repository and file repository. In this section you create and save a dictionary for the Java 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 theCarRepository
file repository in the /dict
directory supplied with the Java How-To.
See Section 2.4.2, "Creating a Rule Author Dictionary" for instructions on how to do this.
In Oracle Business Rules, you store rules and the data model associated with the rules in a dictionary. You create and save dictionaries in a repository.
Note:
If you choose to use a WebDAV 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:
Click the Repository tab.
Click the Connect secondary tab.
Select the WebDAV repository type in the Repository Type field.
Enter the URL to the WebDAV repository (see Figure 2-5). The URL must be in the form:
http://www.fully_qualified_host_name.com:port/repository_name
Note:
In order for authentication to work, you must use a fully qualified host name in the URL.Figure 2-5 Rule Author WebDAV Repository Connect Page
See Section B.1, "Working with a WebDAV Repository" for information on how to setup a WebDAV repository.
If there is a proxy between the system where Rule Author runs and the WebDAV server, then Rule Author also shows the Proxy User and Proxy Password fields.
Click Connect. After you click connect, Rule Author shows a confirmation message (see Figure 2-6).
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.Figure 2-6 Rule Author Repository Connect Page with Confirmation
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.
Note:
It is not safe for multiple users to edit the same dictionary at the same time.To create a dictionary, do the following:
Connect to a repository from the Repository tab.
Click Create.
Enter the dictionary name in the New Dictionary Name field. For this example enter CarRental
(see Figure 2-7).
Click Create. After you click Create, Rule Author shows a confirmation message.
Figure 2-7 Rule Author Create Dictionary Page
Note:
In addition to creating your own dictionary, you can also use the completed car rental dictionary that is supplied with the Java How-To. This dictionary is located in theCarRepository
file repository in the /dict
directory. To use this dictionary, do the following:
Click the Repository tab.
Click the Connect secondary tab.
Select File in the Repository Type box.
Enter the complete path to the file repository in the File Location field. For example, enter C:/demo/dict/CarRepository
.
Click Connect.
To save to a different dictionary name or to specify a version for the current dictionary, use Save As as follows:
Click the Repository tab.
Click the Save As secondary tab.
Enter a dictionary name in the Dictionary field, for example, enter CarRental
.
To specify a version, enter a version in the Version field, for example, HowTo
(see Figure 2-8).
Click Save As. After clicking Save As, Rule Author shows a confirmation message.
Note:
Rule Author allows you to use Save As to overwrite a dictionary with the same name and version. Select the Overwrite check box to save a dictionary with the same name and version.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 because 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 and for details on how Rule Author automatically saves the current work to a dictionary version when a timeout occursBefore 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. To simplify the discussion in this section, we refer to Java fact types as Java facts. In this section you only work with Java facts.
This section covers the following topics:
The Java How-To includes the car-objs.jar
file in the $HowToDir/lib
directory. This jar file includes the Driver
class for the car rental sample. The Java source for the Driver
object is available in the directory $HowToDir/src/carrental
, where $HowToDir is the directory where you installed the Java How-To.
Before you can import Java facts into a data model you must make the classes and packages that contain the Java facts available to Rule Author. To do this, use Rule Author to specify the classpath that contains the Java classes. For example, to add the classpath for the Java class Driver
, do the following:
Click the Repository tab.
Skip to Step 3 if you just created the dictionary as shown in Section 2.4.3. On the Load page, select the CarRental
dictionary and HowTo
version, then and click Load.
Click the Definitions tab. The navigation tree shows the Definitions folder that contains the available definitions. Nothing is shown in the main pane.
Note:
In Rule Author, the bottom pane usually contains a navigation tree and a content area (the main pane). When you select the Definitions tab, the Definitions folder appears at the top of the tree.The Definitions folder in the tree contains the Fact folder, which includes the available fact types: JavaFact, XMLFact, and RLFact.
Click JavaFact to view the JavaFact Summary page (see Figure 2-9).
Figure 2-9 Rule Author Definitions Java Fact Summary Page
Click Create. This shows the Class Selector page.
On the Class Selector page, the User Classpath field lets you add a classpath. For example, for the Java How-To enter the following in the User Classpath field.
$HowToDir/lib/car-objs.jar
Replace $HowToDir with the directory where you installed the Java How-To.
Click Add. This updates the Current Classpaths field and adds the carrental
package to the Classes box (see Figure 2-10).
Figure 2-10 Rule Author JavaFact Class Selector Page
See Also:
Section 2.5.3 for more information about adding Java classes and packages to Rule AuthorNext, you must select the Java classes that you want to import into the data model from the Class Selector page. To add the Driver
class to the data model, do the following:
Click the Definitions tab to view the Definitions page.
In the navigation tree, click the JavaFact folder.
On the JavaFact Summary page, click Create. This shows the Class Selector page.
In the Classes box on the Class Selector page, expand the carrental node and select the Driver check box (see Figure 2-11).
Click Import. After you click import Rule Author shows a confirmation message:
1 class or package has been imported.
Note:
After a class is imported, the class selector page shows the imported class in bold.Figure 2-11 Rule Author JavaFact Class Selector Page
Notes for specifying the user classpath and importing Java classes to Rule Author:
In Rule Author, importing a Java fact means the same thing as a Java import statement. That is, the classes and their methods become visible to Rule Author. Rule Author does not copy the Java code into the data model or into the dictionary.
The Class Selector page includes the Classes box, which shows the Java classes available from the current classpaths.
The default Rule Author classpath includes three packages, java
, javax
, and org
. These packages contain classes that Rule Author lets you import from the Java runtime library (rt.jar). Rule Author does not let you remove these classes from the Classes area (and the associated classpaths are not shown in the Current Classpaths field).
To assign or compare two objects that are not of the same type but are related by inheritance, you must import both classes to be compared and all classes between them in the inheritance hierarchy. For example, if you want to assign an ArrayList
to a variable of type Object
, you must import ArrayList
, AbstractList
, and AbstractCollection
into the data model. Otherwise, type-checking does not work correctly and expressions do not validate.
On Windows systems, you can use a backslash (\
) or a slash (/) to specify the User Classpath. Rule Author accepts either path separator. For example, you can use the following: $HowToDir\lib\car-objs.jar
, where $HowToDir is the directory where you installed the Java How-To.
To improve performance the classes box navigation tree. 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.
Classes and interfaces that you use in Rule Author must adhere to the following rules:
If you are using a class or interface and its superclass, you must declare the superclass first.
If you are using a class or interface, only its superclass or one of its implemented interfaces may be mentioned.
For more information, see Section D.6, "Preserving Class Order and Hierarchies in the Data Model".
In the User Classpath you can specify a jar file, a zip file, or a full path for a directory.
When you specify a directory name for the User Classpath, the directory specifies the classpath that ends with the directory that contains the "root" package (the first package in the full package name). Thus, if the User Classpath specifies a directory, Rule Author looks in that tree for directory names matching the package name structure.
For example, to import a class cool.example.Test1
located in c:\myprj\cool\example\Test1.class
to the data model, specify the User Classpath value, c:\myprj
.
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".
While you are working on the data model from the Definitions tab and when you complete your work, you should save the dictionary.
To save your definitions to the dictionary, do the following:
Click the Save Dictionary link.
Click Save on the Save Dictionary page.
Click the Definitions tab to return to the definitions page.
The business vocabulary allows business analysts working with Rule Author to create rules using familiar names rather than using 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:
To specify the business vocabulary for Java fact definitions, do the following:
Click the Definitions tab to view the Definitions page.
In the navigation tree, click the JavaFact node to display the JavaFact Summary page. For the car rental sample, this shows a table that includes the imported class carrental.Driver
.
Click the edit icon to view the JavaFact Properties and Methods table for the carrental.Driver
class.
At the top of the page, under the Name field, in the Alias box, enter the alias DriverData
in the Alias field for the class carrental.Driver
.
For the age
entry in the Properties table, specify the desired alias. For example, enter DriverAge
in the Alias field.
For the name entry in the Properties table, specify the desired alias. For example, enter DriverName
in the Alias field.
Click OK to save your changes and return to the JavaFact Summary page.
Note:
Be sure to click either OK or Apply after making changes. If you do not click OK or Apply, Rule Author does not save your changes.See Also:
"Viewing Java Objects in a Data Model"To specify the business vocabulary for an RL Language function, do the following:
Click the Definitions tab to view the Definitions page.
In the navigation tree, click RLFunction
in the Definitions folder to display the RLFunction Summary page. For the car rental sample, this shows a table that includes the functions DM.assertXPath
and DM.println
.
For the DM.println
function, click the edit icon to view details.
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 alias field in the Function Arguments Area.Click OK to save your changes and return to the RLFunction Summary page.
Save the dictionary.
To specify whether properties or methods are visible in Rule Author lists, do the following:
Click the Definitions tab to view the Definitions page.
In the navigation tree, click the JavaFact node to display the JavaFact Summary page. For the car rental sample this shows a table that includes the imported class carrental.Driver
.
Click the edit icon to view the JavaFact Properties and Methods table for carrental.Driver
.
For each entry in the Properties table, specify the desired visibility using the Visible check box. For this example, only the member variables age
and name
must be visible.
Click OK to save your changes and return to the JavaFact Summary page.
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, you must mark as visible any non-visible properties or methods causing the problem.In this section, you define a rule for the car rental sample and see the basic steps for creating rules with Rule Author.
This section covers the following topics:
Before you can create a rule using Rule Author, you must create a rule set. A rule set is a container for rules.
To create a rule set, do the following:
Click the Rulesets tab.
Click the RuleSet node in the navigation tree.
On the Ruleset Summary page, click Create. This displays the Ruleset page.
Enter text in the Name field. For example, enter vehicleRent
in the Name field.
Optionally enter a description for the rule set in the Description field (see Figure 2-12).
Click OK to create the vehicleRent
rule set. After you click OK, the new rule set appears in the navigation tree under RuleSet.
Save the dictionary.
After creating a rule set, you can create rules within the rule set. In this section, you create a rule called UnderAge. This rule tests for the following:
If the age of a driver is younger than 21, then decline to rent
The UnderAge rule contains a single pattern for the Rules Engine to match, and a test that is applied to the pattern.
The following actions are associated with the UnderAge rule:
Print the text, "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 object. 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.
To use Rule Author to add the UnderAge rule, do the following:
Click the Rulesets tab. The navigation pane displays the RuleSet folder that contains the vehicleRent
rule set that you created in the section, "Creating a Rule Set for the Car Rental Sample".
Click the vehicleRent folder in the tree. This displays the Ruleset page, with a table listing rules (see Figure 2-13).
Note:
If you have not previously created other rules, then the Rules table is empty.Figure 2-13 Rule Author Ruleset Page Showing the Table of Rules
Click Create. This displays the Rule page.
Enter UnderAge
in the Name field.
Do not change the default value, 0, in the Priority field.
Note:
The Priority field determines the rule priority. Rule priority specifies which rule to act upon, and in what order, if more than one rule applies within a rule set. Often in applications that use rules, the rules in a rule set are applied in any order until a decision is reached, and setting the rule priority is not required.Enter Under age driver rule
in the Description field (see Figure 2-14).
See Also:
Oracle Business Rules Language Reference Guide for more information about working with rule priorityWhen the Rules Engine runs, it checks the facts against rule patterns to find matching patterns. Do the following to add a pattern for the UnderAge rule:
In the If box on the Rule page, click New Pattern. This displays the Pattern Definition page, which contains two areas: Choose Pattern and Define Test for Pattern (see Figure 2-15).
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 2-15 Rule Author Pattern Definition Page
Under Choose Pattern, in the first box select the first choice (this shows no value in the selection box).
This box specifies that the rule should fire each time there is a match (for all matching drivers). One alternate value, There is at least one case, selects one firing of the rule if there is at least one match (one such driver). The value There is no case specifies that the rule fires once if there are no such matches (no matching drivers).
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 value lets you test multiple instances of the same type in a single rule. For example, the pattern bind variable lets you compare a match for a driver with other drivers, using the specified name, in a comparison such as driver1.age
>
driver2.age
.
The third box contains the text <make a choice>
. This box shows the available fact types from the data model. In this box, select DriverData
(if you did not define an alias for this in the data model, then this is carrental.Driver)
.
Click OK or to save the pattern definition and return to the Rule page.
Click OK on the Rule page 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 the pattern definition.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 on the Pattern Definition page, as shown in Section 2.7.2.3.
See Also:
"Adding Actions for the UnderAge Rule"To add a test for a pattern, do the following:
From the Rulesets tab, in the navigation pane click the rule that you want to add a test for. For this example, click the node in the navigation pane for the UnderAge rule. This displays the Rule page.
In the If box on the Rule page, click the pencil icon to display the Pattern Definition page. The Pattern Definition page contains two areas: Choose Pattern and Define Test for Pattern.
On the Pattern Definition page, select the Standard Test button, then click Create (see Figure 2-16). For more information, see Section 3.8.1, "Using the Advanced Test Expression Option".
Figure 2-16 Rule Author Rule Pattern Definition Page with Define Tests for Pattern Fields
In the Operand column, from the first Field box, select driver.DriverAge
(if you did not define an alias for this member variable in the data model, then this is driver.age)
.
In the Operator column, select < (less than).
In the Operand column, in the Value box enter 21. Do not enter a value in the Field box.
Next to the Value and Field boxes is a drop-down list containing the values Any
and Fixed
(see Figure 2-17). These values are called constraints, and they enable or disable customization. Use Fixed
to make the field read-only, which specifies no customization for the field. Select Any
to specify that Rule Author allows changes to the value (this allows nontechnical users to make modifications to the field from the Customization tab).
Select Any
as the constraint for the Value field.
Figure 2-17 Rule Author Pattern Definition Page with Values for the UnderAge Rule
Click OK or save your changes and return to the Rule page.
Click OK on the Rule page.
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 rule set or select a different tab before you click OK or Apply, Rule Author discards the pattern definition.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).
Actions are associated with pattern matches. When the "If" portion of a rule matches, Rules Engine activates the "Then" portion and prepares to run the actions associated with a 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 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.
If 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:
Click the Rulesets tab.
In the tree, under the vehicleRent folder, click the node for the UnderAge rule.
On the Rule page in the Then section, click New Action. This displays the Add Action page (see Figure 2-18).
From the Action Type box, select the Call
item. This shows the Action Parameters box.
From the Function list, choose PrintOutput
(if you did not define an alias for this function, then this is DM.println
). This expands the Function Arguments box.
In the Function Arguments box, in the Argument Value field, in the Expression column, enter a value (see Figure 2-19). For example:
"Rental declined " + driver.DriverName + " Underage,age is:" + driver.DriverAge
Note 1:
Rule Author uses a Java-like syntax for expressions. RL Language defines the complete expression syntax.Note 2:
If you do not know the variable names to use in the expression, use the edit icon in the Wizard field to display the expression Wizard. This presents the Wizard page, which provides more space to write expressions. This also provides an easier and more accurate way to enter variables, because the Wizard presents a variable selection box.Figure 2-19 Rule Author Add Action Page for the UnderAge Rule
Click OK to save your changes and return to the Rule page.
On the Rule page, click OK.
Save the dictionary.
Next, add the retract action for the UnderAge rule. Perform the following steps to add this second action for the rule:
Click the Rulesets tab.
Under the vehicleRent folder, click node for the UnderAge rule.
On the Rule page, from the Then box, click New Action. This displays the Add Action page.
From the Action Type box, select Retract
. This shows the Action Parameters box.
From the Action Parameters area, in the Fact Instance list, select driver
. The pattern name driver
refers to the single instance that was matched by the pattern.
Click OK to save your changes and return to the Rule page.
Click OK on the Rule page (see Figure 2-20).
Note:
Changes made to the action are not added to the rule until you click OK or Apply on the Rule page. If you navigate to a rule set or select a different tab before you click OK or Apply, Rule Author discards the action definition.Save the dictionary.
Figure 2-20 Rule Author UnderAge 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 Table 3-2 for more information on Action Types.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 valid values for the customizable field. 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 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:
Click the Customization tab. The navigation pane displays the vehicleRent folder with the node for the UnderAge rule followed by an asterisk (*), which indicates that the rule is customizable.
In the tree, click the node for the UnderAge rule (see Figure 2-21).
Figure 2-21 Rule Author Rule Customization Page for the UnderAge Rule
On the Rule Customization page, the Customize Patterns box contains an editable text entry field for the test driver.DriverAge < 21
.
In this field, change the value 21
to 19
.
Click Apply.
Save the dictionary.
After you save the dictionary, you are done creating the data model and the rules for the Java How-To.
See Also:
"Defining Tests for Patterns with the UnderAge Rule" for information about the Allowed Values fieldAfter you create and save a dictionary that contains a data model and a rule set with rules, you can use the dictionary in a rule-enabled Java application. This section shows you the steps for creating a rule-enabled Java application.
Note:
Make sure your Java calls are wrapped in a try/catch block.This section covers the following topics:
For the complete code for this sample application, see TestMain.java
in the $HowToDir/src/carrental
directory, where $HowToDir is the directory where you installed the Java How-To.
Note:
The instructions in the preceding sections of this chapter enabled you to create and save a WebDAV repository and dictionary namedCarRental
. The car rental example supplied in the How-To sample code uses a file repository with a dictionary also named CarRental
. The dictionary contents in the WebDAV repository you created in this chapter and the file repository in the How-To sample should be 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.
The first step when you write a rule-enabled program is to import the required classes. Example 2-1 shows the imports from the TestMain.java
application for the car rental sample.
Example 2-1 Required Imports for Car Rental Sample with Rules SDK
import java.util.Date; 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; import carrental.Driver;
When building a rule-enabled Java application, perform the following steps to access a dictionary and specify a rule set (as shown in Example 2-2):
Create a String
that contains the path to the repository.
Use a Rules SDK RuleType
object to hold the repository that you obtain from the RepositoryManager.getRegisteredRepositoryType
method. Example 2-2 shows a file type repository.
Create a repository instance using the RepositoryManager.createRuleRepositoryInstance
method.
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 in Example 2-2.
Use the init
method in the RuleRepository
object repo
to initialize the repository instance.
Example 2-2 Loading a Dictionary with Rules SDK
String fs = "/"; String repoPath = "dict" + fs + "CarRepository"; RepositoryType jarType = RepositoryManager.getRegisteredRepositoryType( Keys.CONNECTION ); RuleRepository repo = RepositoryManager.createRuleRepositoryInstance( jarType ); //fill in initialization property values RepositoryContext jarCtx = new RepositoryContext(); jarCtx.setProperty( oracle.rules.sdk.store.jar.Keys.PATH, repoPath ); //initialize the repository instance. repo.init( jarCtx );
To load a WebDAV repository instead of a file repository as shown in Example 2-2, you should use the getWebDAVRepository
method. The comments include a sample using this method in the program TestMain.java
in the $HowToDir/src/carrental
directory, where $HowToDir is the directory where you installed the Java How-To.
When you build a Java application that uses rules you must load a dictionary with a specified version. Use a RuleDictionary
object to load a dictionary, as shown in Example 2-3, 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.
After loading a dictionary, you need to specify a rule set and use Rules SDK to generate an RL Language program. This step is required, because a dictionary stores a data model and rules using an intermediate XML format. Rules SDK provides methods to access rules and the associated data model. Rules SDK performs the mapping from the intermediate XML format to produce the RL Language program that runs in Rules Engine.
In Rule Author, a rule set includes 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 2-4 shows the code that generates RL Language for these two components.
After you generate an RL Language program that includes 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. A RuleSession
object is the interface between the application and Rules Engine.
Example 2-5 shows the code that creates a RuleSession
object and executes an RL Language program.
The executeRuleset()
method executes an RL Language program passed as a String. This method tells Rules Engine to interpret the specified RL Language program.
Note:
The order of theexecuteRuleset()
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 2-5 Initializing and Executing a Rule Session with Rules SDK
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 specified rule set against the facts that you assert for the rule session.
Before running a rule session, you normally assert some facts. When you execute a data model in a rule session, you prepare the rule session for new facts to be asserted. To assert facts, you use the session.callFunctionWithArgument()
method and the assert
function supplying a fact as an argument.
Example 2-6 shows sample code that prepares Driver
objects for the car rental sample and asserts three facts.
Example 2-6 Preparing Driver and Accident Records for the Car Rental Sample
// Date Function static public Date getDate(String dateStr ) { Date result = null; try { java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat( "MM/DD/YYYY" ); result = sdf.parse( dateStr ); } catch( Throwable t) { t.printStackTrace(); } return result; } // Driver d1 record Date d1LicIssueDate = getDate( "10/1/1969" ); Driver d1 = new Driver( "d111", "Dave", 50, "sports", "full", d1LicIssueDate, 0, 1, true ); // Driver d2 record Date d2LicIssueDate = getDate( "8/1/2004" ); Driver d2 = new Driver( "d222", "Qun", 15, "truck", "provisional", d2LicIssueDate, 0, 0, true ); //Driver d3 record Date d3LicIssueDate = getDate( "6/1/2004" ); Driver d3 = new Driver( "d333", "Lance", 44, "motorcycle", "full", d3LicIssueDate, 0, 1, true ); session.callFunctionWithArgument( "assert", d1 ); session.callFunctionWithArgument( "assert", d2 ); session.callFunctionWithArgument( "assert", d3 );
Example 2-7 shows the code that runs a rule session.
The $HowToDir/lib
directory includes TestMain.jar
, a ready-to-run Oracle Business Rules Java application that uses the CarRental
dictionary. If you change the dictionary name, then you must modify TestMain.java
(the source is available in the directory $HowToDir/src
, where HowToDir is the directory where you installed the Java How-To).
Example 2-8 shows output from running TestMain
using the facts asserted within TestMain
.
Note:
TheReadme.html
file in the $HowToDir/docs
directory includes instructions for setting the environment variables required to run the test program.Example 2-8 Sample Run of the Car Rental Program
java carrental.TestMain Rental declined Qun Under age: age is: 15
Note that not all the facts match the rules and produce output. The example shows the output for the driver, an asserted fact that matches the UnderAge rule.