Skip Headers
Oracle® Fusion Middleware Interaction Management Guide for Oracle WebLogic Portal
10g Release 3 (10.3.4)

Part Number E14238-03
Go to Documentation Home
Home
Go to Table of Contents
Contents
Go to Feedback page
Contact Us

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

10 Creating Advanced Personalization with Rules

Developing Personalization using User Segments, Campaigns, Placeholders, and Content Selectors can be done with JSP tags with very little Java coding. There might be times, however, when you want more flexibility in your Personalization.You can achieve this by creating and deploying a rule set, which uses the Rules Controls and the RulesManager EJB.

This chapter contains the following sections:

The Rules service can help you create advanced Personalization features, which can help control each user's path through a Page Flow or using runtime information as dynamic input to conditional logic in your code. You must possess a working knowledge of XML and schemas (an advanced version of DTDs), as well as an intermediate understanding of Java development.

Note:

Page flows are a feature of Apache Beehive, which is an optional framework that you can integrate with WLP. See "Apache Beehive and Apache Struts Supported Configurations" in the Oracle Fusion Middleware Portal Development Guide for Oracle WebLogic Portal.

10.1 Using Rules in Portal Applications

WebLogic Portal provides a set of tools to personalize the user experience in your portal applications. You have control over the content each user sees, the automatic e-mail messages each receives.

To achieve these Personalization results, you create User Segments, Content Selectors, and Campaigns in Oracle Enterprise Pack for Eclipse. Developing Personalization with these tools involves very little Java coding because you can use JSP tags. After this type of Personalization is developed, portal administrators can use the WebLogic Portal Administration Console to modify the behavior of the Personalization with no coding at all.

There may be times, however, when you want even more power and flexibility in the Personalization you develop. For example, you may want to use Personalization to control each user's path through a Page Flow or use run-time information as dynamic input to conditional logic in your code.

You can access the Rules Service by using the following two types of components:

This overview section includes the following topics:

10.1.1 Choosing Personalization Components

Table 10-1 describes the personalization tools provided by WebLogic Portal. User Segments, Campaigns, Content Selectors, and Personalization JSP tags are described only to highlight the increased programmatic power you have by directly accessing the Rules Service.

The Input Objects and Action columns in Table 10-1 show the flexibility and power you have with the rules controls and the RulesManager EJB.

Table 10-1 WebLogic Portal Personalization Components

Component Description Input Objects Action (if the input objects match the rules criteria)

User Segments

Dynamically assign users to a grouping, or segment, when the users meet specific conditions.

Segment rules are created in Oracle Enterprise Pack for Eclipse with the User Segment Editor. You can modify rules in the WebLogic Portal Administration Console.

Segment rules can be defined with User Profile properties, HTTP session or request properties, and date or time values and ranges.

One action: If all conditions evaluate to true, the user is considered a member of the segment. Segments can be used in Campaigns, Content Selectors, and in the <pz:div> JSP tag.

Campaigns

Trigger personalized actions to occur for users who meet specific conditions or perform specific actions.

Campaign rules are created in Oracle Enterprise Pack for Eclipsewith the Campaign Editor. Rules are modifiable in the WebLogic Portal Administration Console.

Campaign rules can be defined with User Segments, User Profile properties, HTTP session or request properties, event characteristics, date or time values and ranges, and random sampling.

Up to three types of actions: Show a single personalized content item, automatically send a predefined e-mail, provide a discount.

Content Selectors

Show specific content items to users who meet specific conditions.

Content Selector rules are created in Oracle Enterprise Pack for Eclipse with the Content Selector Editor. You can modify rules in the Administration Console.

Content Selector rules can be defined with User Segments, User Profile properties, HTTP session or request properties, and date or time values and ranges.

One action: Show one or more personalized content items.

Personalization (Interaction Management) JSP tags

Some of these tags are used to render the results of segment, Campaign, and Content Selector rules.

Displayed content is based on User Segment, Campaign, or Content Selector rules.

One action: Show personalized content items.

Rules Controls

The Rules Executor control lets you evaluate any input objects (such as a user's profile properties) against a predefined set of rules (rule set). If the rules evaluate to "true" based on the input objects, any predefined action(s) can be triggered (such as assigning the user to a certain classification). The Rules Manager control lets you look up information about rule sets. The rules controls serve as an interface to the RulesManager EJB.

You add and configure rules controls in your Page Flows or Web services with a graphical user interface in Oracle Enterprise Pack for Eclipse. You create rules manually in XML.

Unlimited types of input objects: You can use the rules you create in XML to evaluate any object put into working memory (See Section 10.2.4, "Invoking the Rules Service to Evaluate Objects").

Unlimited types of actions: Can filter objects in working memory (see Section 10.2.5, "Filtering the Results") and perform any action defined in the rule set XML.

RulesManager EJB

Provides the same capabilities as the rules controls in areas of your application other than Page Flows and Web services. Using the RulesManager EJB to access the Rules Service involves Java coding.

Unlimited types of input objects: You can use the rules you create in XML to evaluate any object put into working memory (See Section 10.2.4, "Invoking the Rules Service to Evaluate Objects").

Unlimited types of actions: Can filter objects in working memory (see Section 10.2.5, "Filtering the Results") and perform any action defined in the rule set XML.


10.1.2 Understanding the Rules Service

The Rules Service reads objects you have put into working memory and evaluating those objects against a set of rules you have predefined in an XML file. (Working memory is the place where objects are temporarily stored as the Rules Service is processing the rules.) If the objects in memory match the conditions defined in the rule set (which can be made up of multiple rules), the corresponding rule set actions are triggered. For example, if you put a user's credit score into working memory (from the User Profile, from the return of a Web service calculation, or any other way), a rule in the rule set can be defined in XML to perform the following action: If the user has a credit score equal to or greater than 10, classify that user as a 'gold customer'.

You can use the results of this rule processing in your applications any way you choose. For example, if you are developing a Page Flow, you can send a "gold customer" to the gold.jsp and send all other customers to another JSP.

  • Rules Controls – WebLogic Portal provides two rules controls that you can use to invoke the Rules Service from a Page Flow or Web service. The Rules Executor control lets you evaluate objects in working memory against a rule or set of rules, filter the results, and perform actions if the rules evaluate to true. The Rules Manager control provides methods for getting rule set information.

    Note:

    The Rules Manager control is most useful as a rules development debugging tool.
  • RulesManager EJB – The RulesManager EJB is the interface into the Rules Service. The rules controls delegate calls to the RulesManager EJB. Use the RulesManager EJB if you want to use the Rules Service in code outside of a Page Flow or Web service.

10.1.2.1 Using the Rules Service

The Rules Service is based on the Rete algorithm, which is optimized for forward chaining reasoning. In the rule evaluation process outlined in the following steps, the Rules Executor control is used as an example:

  1. The Portal Rules Service is initialized, creating its working memory.

  2. The Rules Executor control will identify which rule set to use, which rules to evaluate (the default is all), and optionally, whether to filter the results. These are all parameters that can be configured on the control.

  3. The developer creates and adds objects to working memory. Example objects could include the User's Profile, the Request, and so on. These parameters are passed in as an argument to the rule control's evaluate*() method.

  4. The Rules Service is invoked by the Rules Executor control and uses the following algorithm:

    1. Match – Evaluates the left hand side (LHS) of the rules to determine which are satisfied given the current contents of working memory.

    2. Conflict resolution – Selects one rule with a satisfied LHS. If no rules satisfied the LHS, the interpreter is stopped.

    3. Act – Performs the actions in the right hand side (RHS) of the selected rule.

    4. Repeat the process – Go to Step a.

  5. The Rules Service fires repeatedly, executing rules according to the state of the input objects and rule conditions. Only one rule can be fired at a time. As conditions are met and rules are fired, more objects may be added to working memory for evaluation.

  6. After the Rules Service has reached a state where no more rules will fire, it stops. In addition to the original input objects, new objects created as a result of the rule evaluation may also be in working memory.

  7. Because the input objects are part of the results, you may choose to filter the results based on a class. For example, you can specify that only results of Java class com.bea.p13n.usermgmt.profile.ProfileWrapper are returned.

  8. The objects are returned to the caller, who then decides what to do with the returned data. For example, the user may be directed to a new page, or the User's Profile might have its properties updated.

Figure 10-1 provides a basic illustration of the rule evaluation process with the Rules Executor control used in a Page Flow. The returned results from the Rules Service process are used to determine the user's path through the Page Flow. In the figure, natural language is used instead of code for illustration purposes. (To see the actual parameterization and invocation of the control in a Page Flow, see Section 10.2.4.3, "Using the Control to Determine the User's Path in the Page Flow.")

Figure 10-1 Using Rules to Control a Page Flow

Description of Figure 10-1 follows
Description of "Figure 10-1 Using Rules to Control a Page Flow"

10.1.2.2 Understanding the Advantages of Using the Rules Service

The Rules Service is more dynamic than a simple conditional in your code. After a Web application or some other application component has been hard-coded with condition statements (if/then), there is no way to change that without recompiling the code and re-deploying the application. In comparison, rules can be changed and loaded as the Portal server is running. This means the administrator may get the business logic from domain experts, formulate a rule to reflect that logic, and load the rule into the application without ever having to stop the server.

10.2 Creating a Rule

This section shows you how to develop personalization using the rules controls and RulesManager EJB. The following steps are involved and are described in this section:

10.2.1 Creating a Rule Set

Rule sets are sets of instructions written in XML that the Rules Service uses to evaluate objects in working memory. A rule set determines if something in working memory meets certain conditions and performs an action.

There are two methods you can use to create a rule set:

  • Create a rule set in Oracle Enterprise Pack for Eclipse

  • Create a rule set manually

Creating a Rule Set in Oracle Enterprise Pack for Eclipse

You can use Oracle Enterprise Pack for Eclipse to create and manage a .rls file that contains rules, conditions, and actions.

Perform the following steps to create a rule set in Oracle Enterprise Pack for Eclipse:

  1. Start the WebLogic Server in Oracle Enterprise Pack for Eclipse by choosing Run As > Run on Server. For instructions on configuring the WebLogic Server, see the Oracle Fusion Middleware Portal Development Guide for Oracle WebLogic Portal.

  2. In the Portal Perspective, right-click the <data>\src folder in the Package Explorer View and choose New > Rule Set.

  3. Select the folder for the rule set and enter a name for the rule set in the File name field, using the .rls file extension. A rule set can exist anywhere in your data directory.

  4. Click Finish. The rule set appears in the folder you selected.

  5. Select the rule set in the Rule Set Editor.

  6. Select the Properties tab and enter a description for the rule set.

  7. From the Design Palette tab, drag a rule action onto the Rule Set Editor. See Section 8.2.4, "Adding an Action to a Scenario's Rule" for more detail on each action.

  8. In the action, click the all link to toggle back and forth between any and all to determine which conditions will trigger this action. The any choice means that only one of the conditions must be true for the action to occur. Rules can have more than one action.

  9. Click other applicable links and define them.

  10. In the Available Conditions section in the Design Palette tab, select the condition under which the rule set will run and drag the condition to the action. Click the condition's link to define the condition and determine what will trigger the action. See Table 4-1 for more information on conditions. See Figure 10-2 for an example rule set.

Figure 10-2 A Rule Set that Uses The Visitor is a Member of a Predefined User Segment Condition

Description of Figure 10-2 follows
Description of "Figure 10-2 A Rule Set that Uses The Visitor is a Member of a Predefined User Segment Condition"

  1. Save the file by choosing File > Save.

10.2.1.1 Creating a Rule Set Manually

You can create a rule set manually. Rule sets must conform to particular schema. (The rule set schemas are located in the p13n_app.jar file. You can find this file in <WLPORTAL_HOME>\p13n\lib\j2ee-modules\p13n-app-lib.ear.) The language of the rules is actually a usage of the WebLogic Portal expressions package, extended to meet additional requirements for the Rules Service. See the com.bea.p13n.expression.operator.* packages in Oracle Fusion Middleware Java API Reference for Oracle WebLogic Portal for descriptions of the expressions you can use.

Rule set XML files, which must end in .rls, all contain the following required elements:

  • The <rule-set> – Includes all references to schema used in the rule set.

  • The <rule> – Contains the definition of the rule, which consists of at least one condition and at least action. A rule set can have more than one <rule>.

  • The <conditions> and <actions> – Each <rule> contains its own if/then clauses that consist of at least one <condition> (if) and one or more <action> (then). The Rules Service evaluates the objects in working memory against the conditions. If an object meets a condition, the related actions are executed.

Example 10-1 contains a simple rule set example that says, If the string 'Make an Integer 10' is in working memory, add an Integer object '10' to working memory.

Example 10-1 Rule Set that Adds an Object to Working Memory

<?xml version="1.0" encoding="UTF-8"?>
<!-- edited with XMLSPY v5 rel. 4 U (http://www.xmlspy.com) by Your Name (Your Company) -->
<rule-set xmlns="http://www.bea.com/servers/p13n/xsd/rules/core/2.1.1" xmlns:exp="http://www.bea.com/servers/p13n/xsd/expression/expressions/2.1.1" xmlns:literal="http://www.bea.com/servers/p13n/xsd/expression/literal/1.0.1" xmlns:string="http://www.bea.com/servers/p13n/xsd/expression/string/1.0.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/servers/p13n/xsd/rules/core/2.1.1
rules-core-2_1_1.xsd" is-complete="true">
   <rule is-complete="true">
      <name>Add Integer</name>
      <description>Test Rule</description>
      <conditions>
         <exp:equal-to>
            <exp:variable>
                <exp:type-alias>java.lang.String</exp:type-alias>
             </exp:variable>
                <literal:string>Make an Integer 10</literal:string>
             </exp:equal-to>
       </conditions>
       <actions>
           <add-object>
               <exp:type-alias>java.lang.Integer</exp:type-alias>
               <exp:arguments>
                   <literal:string>10</literal:string>
                </exp:arguments>
            </add-object>
       </actions>
   </rule>
</rule-set>

Unless you are adept at reading schemas and manually constructing valid XML according to the schema's rules, use an XML editor such as XMLSpy (which can be installed from the WebLogic Platform product CD). An XML editor reads a schema, as well as all the schemas the schema imports, and shows you elements and attributes that can be added to an XML document at any location, showing you available elements and attributes and helping you create a valid XML rule set.

Before you begin to create the rule set in XML, write out the rule in natural language to understand all its pieces (conditions and actions) and types of data. What is being put into working memory? What conditions do you want the objects to meet, and what should happen (actions) when objects in working memory meet the conditions?

Use the following guidelines to create a rule set (or modify an existing rule set) with an XML editor:

  1. Extract the following schemas from the p13n_app.jar file in the <WLPORTAL_HOME>\p13n\lib\j2ee-modules\p13n-app-lib.ear file into the same directory where you will create your rule set:

    lib/schema/expression*.xsd

    lib/schema/rules*.xsd

  2. Start a new document (or open an existing document) in your XML editor and associate the document with the rules-core-2_1_1.xsd schema. This schema also includes imports of other schemas, especially expression schemas, that are helpful in building rule sets.

    In a new XML document, your XML editor should automatically insert the XML header, automatically import any schemas listed for import, and insert required base elements, such as <rule-set>, <rule>, <name>, <conditions>, and <actions>.

  3. Select the <conditions> and <rules> elements and begin building (or modifying) the conditions and rules.

    Figure 10-3 shows a rule set being built in XMLSpy. With the <exp:greater-than-or-equal-to> element selected, the Elements section shows which elements can be added as children. The Attributes section shows the attributes that can be set on the element.

Figure 10-3 Building a Rule with an XML Editor

Description of Figure 10-3 follows
Description of "Figure 10-3 Building a Rule with an XML Editor"

  1. After you finish building the rule set, use the XML editor's features to check them for being well-formed. Then validate the rule set against the schema. (In XMLSpy, press F7 and F8 to perform these steps.) See Section 10.2.1.3, "Working with Invalid Rule Sets" for instructions on fixing invalid rule sets.

  2. Save the rule set. (XMLSpy prompts you if you are trying to save an invalid rule set, but you can still save it.)

  3. Copy the rule set to your portal application's datasync project directory, or to one of its subdirectories. For example, create a myDatasyncProject/src/rulesets directory and save the rule set there.

10.2.1.2 Using a Method in a Rule

Example 10-2 and Example 10-3 show how an XML rule set uses a method to retrieve a User Profile property value so it can be evaluated by the Rules Service.

Example 10-2 Condition

<exp:greater-than-or-equal-to>
   <literal:integer>10</literal:integer>
   <exp:instance-method>
      <exp:variable>
         <exp:type-alias>User</exp:type-alias>
      </exp:variable>
      <exp:name>getProperty</exp:name>
      <exp:arguments>
         <literal:string>CreditPropertySet</literal:string>
          <literal:string>CreditScore</literal:string>
        </exp:arguments>
    </exp:instance-method>
</exp:greater-than-or-equal-to>

Example 10-3 Method To Which the Condition Maps

ProfileWrapper pw = SessionHelper.getProfile(request);
Object value = pw.getProperty("CreditPropertySet", "CreditScore");

Use the following information when working on the mapping between the XML and the method:

  • The <exp:type-alias> identifies the type of object the method will work on. For a list of object type mappings defined in the parser-mapping-type.properties file in p13n_app.jar, see Section 10.2.3.3, "Using Type Mappings."

  • The <exp:instance-method> indicates a method, and the <exp:name> provides the name of the method.

    Note:

    To invoke methods from a rule, the appropriate classes must be imported in the calling code.
  • The <exp:argument> includes two <literal:string> elements that provide the String arguments to the method.

  • The <literal:integer> identifies a value that the Rules Service uses. The evaluation of the object in working memory (in this case the User Profile CreditScore value) determines if the rule's action is fired.

  • The result is that the rule's condition (in XML) retrieves the value of the user's CreditScore. If the value is greater than or equal to 10, in this example, the associated actions are fired.

10.2.1.3 Working with Invalid Rule Sets

If a rule set does not validate, you can see the invalid area. Perform the following steps to fix the invalid rule set:

  • Verify that you imported all schemas referenced in the .rls file. Those schemas are listed at the top of the *.rls file. The schemas must be in the same directory as the .rls file.

  • Ensure that the XML sections defined in your .rls file are valid according to the schema. You can open the schema in XMLSpy to check your .rls against the schema definitions. In XMLSpy, you can view the schema in Design view for a graphical representation of the schema. You can view the .rls in Text view and Enhanced Grid view.

    Note:

    There is no guarantee that a rule set validated in an XML editor will be validated in the Rules Service.

10.2.2 Deploying a Rule Set

This section explains how to deploy a rule set in development (Oracle Enterprise Pack for Eclipse) and in Staging or Production environments.

This section contains the following topics:

10.2.2.1 Deploying a Rule Set in Oracle Enterprise Pack for Eclipse

After you create a rule set and store it in your application's datasync project directory (or in a subdirectory you create, such as the myDatasyncProject/src/rulesets directory), the rule set is automatically deployed if the server is running. If the server is not running, the rule set is automatically deployed at server startup. (The datasync project directory also contains the User Segments, Content Selectors, Campaigns, and other application metadata you have created.) Rule sets must be deployed to the datasync project directory, and rule set file names must have an .rls extension to be used by the Rules Service.

When you modify a rule set in the datasync project directory, the rule set is automatically refreshed on the running server.

10.2.2.2 Deploying a Rule Set in a Staging or Production Environment

Perform the following steps to add, modify, or remove a rule set that exists in a deployed application:

  1. Modify the rule set in the Development environment and replace it in the deployed application. If the application is in a compressed EAR file, you must recreate the EAR file to include the updated rule set and then replace the EAR file on the server. When you replace the EAR file on the server, you do not need to redeploy the application.

  2. Update the rule set with the Propagation Utility. See the Oracle Fusion Middleware Production Operations Guide for Oracle WebLogic Portal for instructions.

10.2.3 Adding Objects to Working Memory

Rule sets must have objects in working memory to evaluate. For example, a rule set might contain a rule that has the following condition: "If the user's credit score is greater than 10." This implies there is either the credit score input, or there is a way to get at the credit score. We could add a credit score to working memory in one of two ways:

  • Adding the credit score to memory from an integer

  • Adding the credit score to memory from a User Profile

10.2.3.1 Adding a Credit Score to Working Memory from an Integer

You could provide a credit score value in your code in the following ways:

  • Directly – For example, Integer value = new Integer(10);

  • Indirectly – For example, through a form input value:

    Object [] inputObjects = { value }; (This is a required argument to the evaluate*() methods.)

You could then create a rule condition that evaluates the value Integer.

10.2.3.2 Adding a Credit Score to Working Memory from a User Profile

Retrieving a credit score from a User Profile is more flexible and dynamic. First, you would use code to retrieve the User Profile and put it into working memory:

ProfileWrapper pw = SessionHelper.getProfile(request);
Object [] inputObjects = { pw }; (This is a required argument to the evaluate*() methods.)

In your rule set, you would then create a condition that uses a method (getProperty) that retrieves a specific property (CreditScore) from a specific property set (CreditPropertySet). See the example in Example 10-2 and Example 10-3. The condition in the code example checks to see if the retrieved CreditScore is greater than or equal to the <literal:integer> value of 10.

Note:

The User type is actually an alias for an object of class ProfileWrapper. This mapping of User to ProfileWrapper, along with the mappings of other well-known types, are defined in the parser-mapping-type.properties file in the p13n_app.jar file, shown in Section 10.2.3.3, "Using Type Mappings."

10.2.3.3 Using Type Mappings

The following object type mappings are from the parser-mapping-type.properties file in the p13n_app.jar file:

10.2.3.3.1 Using Mappings for <type-alias> Tags

Example 10-4 shows mappings for <type-alias> tags.

Example 10-4 Mappings for <type-alias> Tags

User=com.bea.p13n.usermgmt.profile.ProfileWrapper
Classifier=com.bea.p13n.user.Classification
Capability=com.bea.p13n.entitlements.common.Capability
Role=com.bea.p13n.entitlements.common.Role
Context=com.bea.p13n.rules.internal.engine.Context
Email=com.bea.campaign.rules.MailActionDef
Placeholders=com.bea.campaign.rules.AddAdToPlaceholderActionDef
EndScenario=com.bea.campaign.rules.EndScenarioActionDef
ContentQueryAdvice=com.bea.p13n.content.advislets.ContentQueryAdvice

The code examples in Example 10-1 and Table 10-1 show the <type-alias> element with a User type.

10.2.3.3.2 Mappings for <variable> Tags

Example 10-5 shows mappings for <variable> tags.

Example 10-5 Mappings for <variable> Tags

user=com.bea.p13n.usermgmt.profile.ProfileWrapper
request=com.bea.p13n.http.Request
session=com.bea.p13n.http.Session
event=com.bea.p13n.events.Event
randomNumber=java.lang.Number
classification=com.bea.p13n.user.Classification
date=com.bea.p13n.xml.schema.Date
time=com.bea.p13n.xml.schema.Time
timeInstant=com.bea.p13n.xml.schema.TimeInstant
role=com.bea.p13n.entitlements.common.Role
resource=java.lang.String

10.2.4 Invoking the Rules Service to Evaluate Objects

After you have created a rule set and you have objects in working memory, you can invoke the Rules Service to evaluate the objects in working memory with the rules you created. This section provides an example to show you how to invoke the Rules Service with the Rules Executor control in a Page Flow.

10.2.4.1 Using an Existing Rule Set

The example used throughout the Section 10.2.4, "Invoking the Rules Service to Evaluate Objects" section assumes that a rule set already exists in the /data/rulesets directory that classifies users as "GoldCardMembers" or "SilverCardMembers" by reading a User's Profile (similar to the example used in Section 10.2.3.2, "Adding a Credit Score to Working Memory from a User Profile"). The Page Flow example in this section shows the User Profile being added to working memory. Since the User's Profile is needed in this example, you should assume the Profile Control was added to an existing Page Flow to enable the getting and setting of User Profile properties.

This sample also uses the User Login Control for authentication so that the Page Flow knows which User Profile to retrieve.

For instructions on creating a Page Flow and adding a Portal Control to the Page Flow, see the Oracle Fusion Middleware Java API Reference for Oracle WebLogic Portal.

10.2.4.2 Inserting the Control in the Page Flow

When you insert a control in a Page Flow (a .jpf file in Oracle Enterprise Pack for Eclipse), all the Actions that are part of that control are available to use.

Note:

Page flows are a feature of Apache Beehive, which is an optional framework that you can integrate with WLP. See "Apache Beehive and Apache Struts Supported Configurations" in the Oracle Fusion Middleware Portal Development Guide for Oracle WebLogic Portal.

The Rules Executor Control contains two actions:

  • The evaluateRule Action – Lets you evaluate the objects in working memory against a single rule in a rule set.

  • The evaluateRuleSet Action – Lets you evaluate the objects in working memory against all rules in a rule set.

When you are looking at a Page Flow in Action View, you can select a control you have inserted (by selecting the control's border) and set properties on that control. The Property Editor is a convenient way to send arguments to the RulesManager EJB (which interfaces directly with the Rules Service) without writing Java code.

For example, Table 10-2 shows how the Rules Executor Control properties shown in Figure 10-1 map to method and constructor arguments in the RulesManager EJB.

Table 10-2 How Control Properties Map to Method and Constructor Arguments

Rules Executor Control properties Methods and Constructors

rulesetUri

ruleName

filterResults

filterClassName

filterClassNames

  • evaluateRule(String ruleSetUri, String ruleName, Object[] inputObjects)

  • evaluateRule(String ruleSetUri, String ruleName, Object[] inputObjects, ObjectFilter filter)

  • evaluateRuleSet(String ruleSetUri, Object[] inputObjects)

  • evaluateRuleSet(String ruleSetUri, Object[] inputObjects, ObjectFilter filter)

For details on these RulesManager EJB methods, see com.bea.p13n.rules.manager in the Oracle Fusion Middleware Java API Reference for Oracle WebLogic Portal.

filterRuleName

  • RuleResultClassFilter(String ruleName, Class targetClass)

  • RuleResultClassFilter(String ruleName, Class[] targetClassArray)

For details on these filter constructors, see com.bea.p13n.rules.manager.RuleResultClassFilter in the Oracle Fusion Middleware Java API Reference for Oracle WebLogic Portal.


The RulesManager EJB has the same Actions contained in the Rules Executor Control: evaluateRule() and evaluateRuleSet(). The difference is that the Rules Executor Control Actions take only one argument—for example, evaluateRuleSet(Object[] inputObjects)—and provide the rule and filter arguments through the control properties.

If you set the filterResults property to true on the Rules Executor Control, the EJB method with the filter argument is used and the filtering properties you enter are automatically sent to that argument.

The filterClassName and filterClassNames properties are different options for populating the filter argument (with one or more types of filters). Set either filterClassName or filterClassNames on the control, but do not set both.

Use the filterRuleName property to filter on the results of a specific rule in a rule set that has fired. If you use this property, the RuleResultClassFilter constructor is called. Notice that the constructor is overloaded to use either a single class filter (that you entered in the filterClassName) property or multiple class filters (that you entered in the filterClassNames) property. The result of using the filterRuleName property is that you not only filter the results of a specific rule that has fired, you can also filter on specific data types.

Following are more detailed definitions of the control properties:

  • The rulesetUri (required) URI of the rule set to use – This URI is relative to the application's datasync project directory. For example, if you created a rule set called myruleset.rls and stored it in a myDatasyncProject/rulesets directory, the URI would be /rulesets/myruleset.rls. Use the Rules Manger Control to list rule sets and rules.

  • The ruleName (optional) Name of the rule to use –The rule must be contained in the rule set specified in the rulesetUri property. If not specified, all the rules in the rule set are evaluated. The default is null.

  • The filterResults (optional) – This property determines whether to filter the results after the rules have been evaluated. If the value is false, all objects remaining in working memory are returned. The default is false. For information on filtering, see Section 10.2.5, "Filtering the Results."

  • The filterClassName (optional) – Enter the class name (for example, java.lang.String) of the type of results to return. If this is left empty, results are not filtered. Specify this or the filterClassNames, but not both.

  • The filterClassNames (optional) – Enter a comma-separated list of class names of the types of results to return (for example, java.lang.String,java.lang.Integer). If this is left empty, results are not filtered. Specify this or the filterClassName, but not both.

  • The filterRuleName (optional) – Filter the results of a specific rule that was fired. If this is left empty, results from all rules will be returned. Otherwise, results from only this rule are returned. This filter is applied with the Class filters, if those are specified.

10.2.4.2.1 Understanding the Benefits of Using the Control

Understanding how properties map to methods and constructors can help you understand the benefits of using the Rules Executor control. Filling in property values provides the following benefits:

  • You do not have to write Java code

  • If you are filtering the results, the filter is constructed automatically for you

For more information on the Rules Executor Control, see the Oracle Fusion Middleware Java API Reference for Oracle WebLogic Portal.

10.2.4.3 Using the Control to Determine the User's Path in the Page Flow

After you add the Rules Executor Control to the Page Flow, set the properties on the control, and select one of the control's execute* actions to use, you should verify that all other prerequisite details are in place (see Section 10.2.4.1, "Using an Existing Rule Set"). Then you can add code to the Page Flow that sends users to a different page depending on the classification they receive from the rule evaluation process.

The sample Page Flow code in Example 10-6 shows how a user is directed to a particular page based on the results from the Rules Service.

Example 10-6 Sample Code to Direct a User to a Page, Based on the Results of the Rules Service

public class Controller extends PageFlowController
{
    /**
    * @common:control
    */
    private com.bea.p13n.controls.login.UserLoginControl userLoginControl;
    /**
    * @common:control
    */
    private com.bea.p13n.controls.profile.ProfileControl myProfileControl;
// The Rules Executor control is added. Properties are configured
// in the Property Editor.
// This is all done in the Page Flow's Action View.
    /**
    * @common:control
    * @jc:rules-executor filterClassName="com.bea.p13n.user.Classification"
filterResults="true" rulesetUri="/rulesets/myruleset.rls"
    */
    private com.bea.p13n.controls.rules.RulesExecutorControl
    myRulesExecutorControl;
    /**
    * @jpf:action
    * @jpf:forward name="default" path="default.jsp"
    * @jpf:forward name="goldCard" path="goldCard.jsp"
    * @jpf:forward name="silverCard" path="silverCard.jsp"
    * @jpf:catch type="com.bea.p13n.controls.exceptions.P13nControlException" path="error.jsp"
    * @jpf:forward name="error" path="error.jsp"
    */
    protected Forward evaulateRuleSetAction(EvaluateRuleSetActionForm form)
    throws P13nControlException
    {
// Start with an empty list into which we add objects to populate
// the working memory of the Rules Service
        List wmObjects = new ArrayList();
        ProfileWrapper pw = myProfileControl.getProfileFromRequest(this.getRequest());
        if ( pw == null)
        {
            throw new P13nControlException("Undable to retrieve profile from
            request. " + "Make sure PortalServletFilter is configured 
            in web.xml for an anonymous user, " + "or that a user 
            has logged in.");
        }
// This one will be the condition that fires the rule
        Integer value = new Integer(6);
        myProfileControl.setProperty(pw, "FooPropertySet", "CreditScore", value);
        wmObjects.add(pw);
// Evaulate all rules in the rule set. Parameters have been declared on the
// control in the Page Flow Property Editor (in Action View).
        Iterator iter = myRulesExecutorControl.evaluateRuleSet(wmObjects.toArray());
        List results = new ArrayList();
// Let's say we're looking for GoldCardMembers
        Classification goldCardMembers = new Classification("GoldCardMembers");
        Classification silverCardMembers = new Classification("SilverCardMembers");
// And we'll direct them to a certain page depending 
// on how the rule evaluates
        Classification classification = (Classification)iter.next();
// Now you would do something with that,
// like show them a different page
        if (classification.equals(goldCardMembers))
        {
// Direct them to high-price stuff
            return new Forward("goldCard");
        }
        else if (classification.equals(silverCardMembers))
        {
// Direct them to lower-price stuff
            return new Forward("silverCard");
        }
// Otherwise, it defaults. Something went wrong.
// Check the rule conditions or turn off filtering on the control 
// to see what's in working memory
        }
    }
    return new Forward("default");
}

If you want to use only a specific type of object in working memory after the Rules Service has stopped, you can filter the objects in working memory. Filtering is set using Java types. On the Rules Executor Control, you can set the filter type in the Property Editor.

Get more information on the following subjects:

10.2.5 Filtering the Results

When you execute the Rules Service to evaluate objects in working memory, as described in Section 10.2.4, "Invoking the Rules Service to Evaluate Objects," you can filter the objects in working memory when the Rules Service has stopped running to return only the objects of a specific type.

Objects exist in working memory as a result of one of the following actions:

  • The caller puts them there (in the inputObjects array)

  • A new object is instantiated in one of the rules' actions

When the Rules Service has stopped, several objects might remain in working memory, including those the user initially added. For example, your rule may instantiate a new Classification object into working memory if the rule evaluates to true. Another example is that a rule action might have updated the User's Profile, so you need to retrieve the profile from working memory.

When the Rules Service's API executes a rule, it returns an Iterator over the entire contents of working memory unless you filter the results. If you are looking only for Classification objects, then you can specify a filter that returns only Classification objects. You can design this filter based on a single class name, multiple class names, or a given rule, as described in Section 10.2.4.2, "Inserting the Control in the Page Flow."

When you implement the Rules Executor Control, the control takes care of constructing the filter automatically. You need to specify whether to filter and the filter class names as control properties. The filter is applied for you automatically by the control, if you specify this.

10.2.5.1 Filtering with the RulesManager EJB

Filtering with the RulesManager EJB is a more cumbersome than filtering with the Rules Service, because you must design the filter yourself with the RulesManager EJB. Example 10-7 shows how to design a filter.

Example 10-7 Design a Filter with the RulesManager EJB

String filterRuleName = null;
Class filterClass = com.bea.p13n.user.Classification.class;
ObjectFilter filter = new RuleResultClassFilter(filterRuleName, filterClass);
Class [] filterClasses = { java.lang.String.class, com.bea.p13n.usermgmt.profile.ProfileWrapper.class};
ObjectFilter filter = new RuleResultClassFilter(filterRuleName, filterClasses);

The filter can then be used as part of the RulesManager EJB, as shown in the following example:

public Iterator evaluateRule(String ruleSetUri, String ruleName, Object[] inputObjects, ObjectFilter filter)

If you filtered the results, the Iterator should only contain results of the class types you specified. The code sample in Example 10-8 shows a Classification object of SilverCardMembers.

Example 10-8 Sample Code that Retrieves Silver Card Members

while (iter.hasNext())
{
Classification c = (Classification)iter.next(); 
     if (c.equals(silverCardMembers)) 
     {  
          // do something 
     } 
} 

10.2.6 Using the Results in Your Application

The Rules Service makes decisions for you at run-time. The rules framework is more flexible than hard-coding logic (if/then) into your components, because you can modify rules without modifying your code.

Following are some examples of using rules and rule results:

  • If the time is between 8-5, direct users to pages that relate to brokerage services. If the time is outside the range, direct users to pages related to investment research.

  • If the user lives in Boulder and is female, show her an advertisement for the Boulder Rock Club.

  • If the user's credit score is > 10, the User Profile (sets a property) to classify the user as a Gold Member.

  • If the date is between December 1 and December 31, send the user to the New Year's promotional JSP.

10.3 Rules Control Reference

You can use the Rules Control elements to provide Personalization in your portal application. Table 10-3 lists the control names and all possible values you can use to create rules.

Table 10-3 Rules Control Elements for the Rules Engine

Rules Control Name Description All Possible Values

rule-set

The root element that contains all of the rules.

rule

rule

The definition of a rule using conditions and actions, along with an optional description.

name, description, conditions, actions

name

The name of the rule.

Any text

description

Optional text describing the rule.

Any text

conditions

Expressions that the Rules Service evaluates using the objects in working memory.

variable, literal, branch, operator, method

variable

Indicates the type of the object being compared in an expression.

N/A

type-alias

A string specifying the kind of a an object or variable

For variables, the value can be any type, such as java.lang.String, or an alias to a variable type from the list below:

user=com.bea.p13n.usermgmt.profile.ProfileWrapper

request=com.bea.p13n.http.Request

session=com.bea.p13n.http.Session

event=com.bea.p13n.events.Event

randomNumber=java.lang.Number

classification=com.bea.p13n.user.Classification

date=com.bea.p13n.xml.schema.Date

time=com.bea.p13n.xml.schema.Time

timeInstant=com.bea.p13n.xml.schema.TimeInstant

role=com.bea.p13n.entitlements.common.

Roleresource=java.lang.String

For objects, the value can be any type, such as java.lang.String, or an alias to an object type from the list below:

User=com.bea.p13n.usermgmt.profile.ProfileWrapper

Classifier=com.bea.p13n.user.Classification

Capability=com.bea.p13n.entitlements.common.

Capability

Role=com.bea.p13n.entitlements.common.Role

Context=com.bea.p13n.rules.internal.engine.Context

Email=com.bea.campaign.rules.MailActionDef

Placeholders=com.bea.campaign.rules.

AddAdToPlaceholderActionDef

EndScenario=com.bea.campaign.rules.

EndScenarioActionDef

ContentQueryAdvice=com.bea.p13n.content.advislets.

ContentQueryAdvice

literal

Used to specify a particular, unchanging value

boolean, character, decimal, double, float, integer, long, string

branch

Controls the execution path within a rule.

if

if

Evaluates expressions to control execution path within a rule.

Any two or three other expressions that evaluate to true or false.

operator

Indicates what sort of comparison will be made in the expression.

and, equal-to, greater-than, greater-than-or-equal-to, less-than,

less-than-or-equal-to, multi-and, multi-or, not, not-equal-to, or

and

To evaluate to true, both expressions must evaluate to true.

N/A

equal-to

Evaluates to true when both expressions are equivalent.

N/A

greater-than

Evaluates to true when the first expression is more than the second expression.

N/A

greater-than-

or-equal-to

Evaluates to true when the first expression is more than or the same as the second expression.

N/A

less-than

Evaluates to true when the first expression is less than the second expression.

N/A

less-than-or-

equal-to

Evaluates to true when the first expression is less than or the same as the second expression.

N/A

multi-and

Evaluates to true when all of the supplied expressions evaluate to true.

N/A

multi-or

Evaluates to true when any of the supplied expressions evaluate to true.

N/A

not

Negates the logical value of one expression.

N/A

not-equal-to

Evaluates to true when both expressions are not equivalent.

N/A

or

Evaluates to true when either expression evaluates to true.

N/A

method

An abstract, complex type.

static-method, instance-method, new-instance, contains, contains-all, abs, acos, add, asin, atan, atan2, ceil, cos, divide, exp. floor, ieee-remainder, log, maximum, minimum, multiply, pow, rint, round, sin, sqrt, subtract, tan, to-degrees, to-radians, char-at, compare-to-ignore-case, concat, ends-with, equals-ignore-case, length, like, replace, starts-with, substring, to-lower-case, to-upper-case, trim

static-method

Invokes the named method on an object in working memory of the type specified by the type-alias, passing any provided arguments to the method.

type-alias, name, arguments

instance-

method

Invokes the named method on an object in working memory of the type specified by the variable type-alias, passing any provided arguments to the method.

variable, name, arguments

new-instance

Instantiates an object of the type specified in the type-alias. Arguments are supplied as expressions, and the type of each argument is specified in the type-alias list in the arguments- signature.

type-alias, arguments-signature, arguments

contains

Returns a boolean indicating if the first Collection object contains the second object.

N/A

contains-all

Returns a boolean indicating if the first Collection object contains the entire second Collection object.

N/A

abs

Absolute value operator, accepting a number and returning a number.

N/A

acos

Arc cosine operator, accepting a number and returning a number.

N/A

add

Addition operator, accepting two numbers and returning their sum.

N/A

asin

Arc sine operator, accepting a number and returning a number.

N/A

atan

Arc tangent operator, accepting a number and returning a number.

N/A

atan2

Cartesian to polar coordinates operator, accepting two numbers and returning a number.

N/A

ceil

Ceiling operator, accepting a number and returning a number.

N/A

cos

Cosine operator, accepting a number and returning a number.

N/A

divide

Division operator, accepting two numbers and returning a number.

N/A

exp

Exponential operator, accepting a number and returning a number.

N/A

floor

Floor operator, accepting a number and returning a number.

N/A

ieee-

remainder

IEEE 754 remainder operator, accepting two numbers and returning a number.

N/A

log

Natural logarithm operator, accepting a number and returning a number.

N/A

maximum

Maximum operator, accepting two numbers and returning a number.

N/A

minimum

Minimum operator, accepting two numbers and returning a number.

N/A

multiply

Multiplication operator, accepting two numbers and returning a number.

N/A

pow

Power of operator, accepting two numbers and returning a number.

N/A

random-

number

Random number operator, optionally accepts a lower and upper bound and returns a random number.

N/A

rint

Round to next integer operator, accepting a number and returning a number.

N/A

round

Round operator, accepting a number and returning a number.

N/A

sin

Sine operator, accepting a number and returning a number.

N/A

sqrt

Square root operator, accepting a number and returning a number.

N/A

subtract

Subtraction operator, accepting two numbers and returning a number.

N/A

tan

Arc tangent operator, accepting a number and returning a number.

N/A

to-degrees

Radians to degrees operator, accepting a number and returning a number.

N/A

to-radians

Degrees to radians operator, accepting a number and returning a number.

N/A

char-at

Returns the character at the given position within the string, accepting a string and a number then returning a character.

N/A

compare-to-

ignore-case

String comparison operator that ignores case, accepting two strings and returning an integer.

N/A

concat

String concatenation operator, accepting two strings and returning a string.

N/A

ends-with

Returns a boolean indicating if the first string ends with the second string.

N/A

equals-ignore-case

Returns a boolean indicating if the first string is the same as the second string, ignoring case.

N/A

length

Accepts a string and returns an integer representing the number of characters in the string.

N/A

like

Returns a boolean indicating if the second string is contained in the first string, ignoring case.

N/A

replace

Accepts a string and two characters, returning a string that has the first character replaced by the second.

N/A

starts-with

Returns a boolean indicating if the first string starts with the second string.

N/A

substring

Accepts a string and two numbers, returning a string of the characters that fall within that number range from inside the given string.

N/A

to-lower-case

Accepts a string, returning that same string converted to lower case.

N/A

to-upper-case

Accepts a string, returning that same string converted to upper case.

N/A

trim

Accepts a string, returning that same string but with any leading or trailing whitespace removed.

N/A

actions

Instructions that are executed if the conditions are met. A group of zero or more action tags.

action

action

One instruction that is executed if the conditions are met.

action (nested), method (defined above), add-object

add-object

Adds an object of the type specified in the type-alias to working memory. Arguments are supplied as expressions, and the type of each argument is specified in the type-alias list in the arguments- signature. This is same functional definition as add instance above.

type-alias, arguments-signature, arguments