Skip Headers
Oracle® Business Rules Language Reference
10g Release 3 (10.1.3)
B15985-01
  Go To Documentation Library
Home
Go To Product List
Solution Area
Go To Table Of Contents
Contents
Go To Index
Index

Previous
Previous
Next
Next
 

4 Using a RuleSession

This chapter includes the following sections:

4.1 RuleSession Constructor Properties

This section shows you the steps for creating a rule enabled application and describes using a RuleSession object. The package oracle.rules.rl contains the RuleSession object.

The RuleSession no argument constructor returns a RuleSession with the default locale, logging, and DMS options set.

Table 4-1 shows the RuleSession constructor properties.

Table 4-1 RuleSession Properties

Property Name Property Value

oracle.rules.rl.configLocale

A Locale object for the desired Locale. If not present in the map, the default Locale is used.

Default Value: the JVM default Locale.

oracle.rules.rl.configSessionName

A name to associate with the RuleSession.

Default Value: the default is a generated name that should be unique.

oracle.rules.rl.configLogging

A Boolean value. If this property is present and the value is true, logging is enabled.

Default Value: false

oracle.rules.rl.configDMS

A Boolean value. If this property is present and the value is true, DMS is enabled.

Default Value: false

oracle.rules.rl.configAppName

A String with the name of the application or component that is instantiating this session. This is only used for DMS metrics. Within OC4J, a component name may be obtained using MBeanServerFactory.createMBeanServer().getDefaultDomain().

Default Value: there is no default value. If this is missing, then that component is missing from the DMS metric hierarchy.


4.2 RuleSession Methods

The outputWriter property determines where println, watch, and show output goes.

The rulesetName property sets the ruleset in the event that RL statements are executed without an explicit named ruleset. The default rulesetName is main.

The executeRuleset methods parse and execute the given ruleset text (given as a String or a java.io.Reader).

The callFunction method invokes the named RL function (which must either be a built-in RL function or must have been previously defined with no parameters using one of the executeRuleset methods) and returns its result. Functions with a single argument can be invoked with the callFunctionWithArgument method. Functions taking any number of arguments can be called using the callFunctionWithArgumentList or callFunctionWithArgumentArray methods. The argument List or array must contain a Java Object for each RL function parameter.

4.3 RL to Java Type Conversion

Table 4-2 describes how Java Object types are be converted to RL types for passing arguments to RL functions, and conversely how RL types are converted to Java types for passing the RL function return value to Java.

Table 4-2 RL to Java Object Conversion

Java Class RL Type

java.lang.Integer

int

java.lang.Character

char

java.lang.Byte

byte

java.lang.Short

short

java.lang.Long

long

java.lang.Double

double

java.lang.Float

float

java.lang.Boolean

boolean

Object

Object

int[]

int[]

char[]

char[]

byte[]

byte[]

short[]

short[]

long[]

long[]

double[]

double[]

float[]

float[]

boolean[]

boolean[]

Object[]

Object[]


4.4 RL Exceptions

The RuleSession parse and execute methods may throw an RLException. The getMessage method returns a formatted error message containing the description of the error, the RL source ("main" or included URL), line number, and column number. Each of these error components can also be accessed separately. Sometimes an RLException is caused by another error (in general, a Throwable object). This underlying cause, if any, can also be accessed.

The package oracle.rules.rl.exceptions contains the exceptions. The RLException class has many subclasses that further categorize the nature of the exception, as shown in the following hierarchy:

RLException
   ParseException - a syntax error
   TypeCheckException - a semantic error
      ArrayException - array expected
      AssignmentException - invalid assignment target
      ConstructorException - can't find constructor for Java class
      ContextException - construct invalid in given context
      ConversionException - can't convert between given types
      FinalClassException - attempt to extend a final fact class 
      InvocationException - illegal function or method invocation
       HiddenPropertyException - fact class for subclass attempted to expose a hidden property or vice versa
      MemberException - property or method not a member of class
      MultipleDefinitionException - symbol defined more than once
      OperationException - operator applied to wrong types. For example, String * String 
      UndefinedException - symbol is not defined
       VisibilityException - class or member referenced outside of defining ruleset or package is not public

RLRuntimeException - runtime error
    RLXPathException - error in  assertXPath function
    RLXmlNameException - error in xml identifier syntax      
    EngineException - internal rule engine error
     JavaException - an invoked Java method threw an exception, call getCause() to access the exception
    RLArithmeticException - an RL arithmetic operation resulted in a divide by zero.
     RLArrayIndexOutOfBoundsException - an attempt was made to index into an array with an index outside the
                                        allocated array
     RLArrayStoreException - an attempt has been made to store the wrong type of object into an RL array of  
                             objects
     RLClassCastException - in an RL expression, at attempt has been made to cast an object to a subclass of
                            which it is not an instance
     RLCloneNotSupportedException - a property of an object asserted as a fact appeared to be cloneable but did
                                    not implement the clone method
     RLIllegalArgumentException - an attempt was made to pass an illegal argument to a builtin RL function or to
                                  a rule engine Java method
     RLNegativeArraySizeException - an attempt was made to allocate an array with a negative size
     RLNullPointerException - an RL expression attempted to dereference a null object or null array reference


The following exceptions are always wrapped with either a RLRuntimeException or TypeCheckException:

4.5 Error Handling

RuleSession method invocations that throw a ParseException or TypeCheckException do not affect the state of the RuleSession. A Java application, for example, an interactive command-line, can catch these exceptions and continue using the RuleSession.

RuleSession method invocations that throw a RLRuntimeException may have affected the state of the RuleSession and the RuleSession may not be in a usable state for the application to proceed. Robust applications should attempt to catch and recover from RLRuntimeExceptions in RL at a point near where the exception is thrown.

Other exceptions likely indicate a serious problem that the application cannot handle.

4.6 RL Class Reflection

You can use an RL class like a Java class in an RL program. The new, instanceof, and cast operators work on both kinds of class. However, when an instance of an RL class is passed to a Java program, it is actually an instance of oracle.rules.rl.RLObject. A Java program can use the following classes: RLClass, RLProperty, and RLArray to examine the RLObject in a manner similar to using the java.lang.Class, java.lang.reflect.Field, and java.lang.Array classes to reflect a java.lang.Object. The package oracle.rules.rl contains RLCLass, RLProperty, and RLArray.

4.7 XML Navigation

XLink objects are created and asserted as facts by the assertXPath function. An RL rule can use XLinks to reason about the hierarchy of elements asserted by assertXPath.


See Also:

"xpath Support"

4.8 Obtaining Results from a Rule Enabled Program

When you create a a rule enabled program with Oracle Business Rules, a common question is, "How do I get the results of the evaluation?"

This section one approaches to extracting or exposing results of rule evaluation from the rule engine.

This section covers the following:


See Also:

3.11 Invoking Rules, in Oracle Business Rules User's Guide

4.8.1 Overview of Results Examples

The examples in this section show a highway incident notification system. These examples show the different approaches to access the results of rule engine evaluation. The examples use two Java classes: traffic.TrafficIncident and traffic.IncidentSubscription.


Note:

The traffic.* sample classes are not included in the Oracle Business Rules distribution.

The TrafficIncident class represents information about an incident affecting traffic and contains the following properties:

  • Which highway

  • Which direction

  • Type of incident

  • Time incident occurred

  • Estimated delay in minutes

The IncidentSubscription class describes a subscription to notifications for incidents on a particular highway and contains the following properties:

  • Subscriber - the name of the subscriber

  • The highway

  • The direction

In the example using these classes, when an incident occurs that affects traffic on a highway, a TrafficIncident object is asserted and rule evaluation determines to whom notifications are sent.

In the examples, the sess object is a RuleSession and a number of incident subscriptions are asserted. As a simplification, it is assumed that the TrafficIncident objects are short lived. They are effectively an event that gets asserted and only those subscribers registered at that time are notified.

The classes in these examples are all Java classes. However, it is possible to manipulate instances of RL classes in Java using the RL class reflection.


See Also:

For documentation see the Javadoc for the RLClass, RLObject, RLProperty and RLArray classes in the oracle.rules.rl package. Thus, RL objects, or instances of RL classes, can be used to hold rule engine results as well as Java objects.

4.8.2 Using External Resources to Obtain Results

This approach is similar to asserting a container for results, except that instead of a container, the object is a means to affecting resources external to the rules engine. For example, this could involve queuing up or scheduling work to be done, updating a database, sending a message. Any Java method accessible in the action may be invoked to effect the results. As with the container use case, the objects used to in this example to access the external resources are not re-asserted since their content is not being reasoned on.

Example 4-1 shows the IncidentDispatcher object that is asserted and then used to dispatch the notification.

Example 4-1 Obtaining Results Using External Resources

    rule incidentAlert
    {
        if (fact TrafficIncident ti &&
            fact IncidentSubscription s &&
                 s.highway == ti.highway &&
                 s.direction == ti.direction &&
            fact IncidentDispatcher dispatcher)
        {
            dispatcher.dispatch(s.subscriber, ti);
        }
    }

Example 4-2 shows Java code that asserts an IncidentDispatcher and a TrafficIncident, and then invokes the rule engine. This could also be accomplished using an object that is being reasoned on, but this would require a test in the rule condition to avoid an infinite loop of rule firing.

Example 4-2 Sample Showing Results with External Resources

        sess.callFunctionWithArgument("assert", new IncidentDispatcher());
 
        // An accident has happened
        TrafficIncident ti = new TrafficIncident();
        ti.setHighway("I5");
        ti.setDirection("south");
        ti.setIncident("accident");
        ti.setWhen(new GregorianCalendar(2005, 1, 25, 5, 4));
        ti.setDelay(45);
 
        sess.callFunctionWithArgument("assert", ti);
        sess.callFunction("run");