ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button

Give Your Business Logic a Framework with Drools
Pages: 1, 2, 3, 4, 5, 6, 7

We run BusinessRuleTest through the JUnit extension of our favorite IDE. If you're not familiar with JUnit, more information can be found at JUnit's website. Not surprisingly, our test fails at the second assertion, shown in Figure 2, as we don't (yet) have the appropriate business logic in place. This is reassuring, as it shows that our simulator/unit tests are highlighting the problems that they should.

JUnit Test Results
Figure 2. JUnit test results

Writing the Business Logic using Rules

At this point, we need to write some business logic that says, "If the stock price is less than 100 Euro, then we should buy it." To do this, we will modify BusinessLayer.java to read:

import java.io.IOException;
import org.drools.DroolsException;
import org.drools.RuleBase;
import org.drools.WorkingMemory;
import org.drools.event.DebugWorkingMemoryEventListener;
import org.drools.io.RuleBaseLoader;
import org.xml.sax.SAXException;
 * Facade for the Business Logic in our example.
 * In this simple example, all our business logic
 * is contained in this class but in reality it 
 * would delegate to other classes as required.
 * @author default
public class BusinessLayer {
  //Name of the file containing the rules
  private static final String BUSINESS_RULE_FILE=
  //Internal handle to rule base
  private static RuleBase businessRules = null;
   * Load the business rules if we have not 
   * already done so.
   * @throws Exception - normally we try to 
   *          recover from these
  private static void loadRules()
                       throws Exception{
    if (businessRules==null){
      businessRules = RuleBaseLoader.loadFromUrl(
          BUSINESS_RULE_FILE ) );
   * Evaluate whether or not to purchase stock.
   * @param stockToBuy
   * @return true if the recommendation is to buy
   * @throws Exception
  public static void evaluateStockPurchase
       (StockOffer stockToBuy) throws Exception{
    //Ensure that the business rules are loaded
    //Some logging of what is going on
    System.out.println( "FIRE RULES" );
    System.out.println( "----------" );
    //Clear any state from previous runs 
    WorkingMemory workingMemory 
            = businessRules.newWorkingMemory();
    //Small ruleset, OK to add a debug listener 
      new DebugWorkingMemoryEventListener());
    //Let the rule engine know about the facts
    //Let the rule engine do its stuff!!

Pages: 1, 2, 3, 4, 5, 6, 7

Next Pagearrow