| Sign In/My Account | View Cart |
Give Your Business Logic a Framework with Drools
Pages: 1, 2, 3, 4, 5, 6, 7
This class now has some important methods:
loadRules(), which loads the rules from the
BusinessRules.drl file.evaluateStockPurchase(), which evaluates
these business rules. Some points to note about this method are:
RuleSet over and over (as
business rules in memory are stateless).WorkingMemory for every evaluation,
as this is our knowledge of what we know to be true at this time.
We use assertObject() to place known facts (as Java
Objects) into this memory.fireAllRules() method on the working memory
class causes the rules to be evaluated and updated (in this case,
stock offer).Before we can run the example again, we need to create our BusinessRules.drl file, as follows:
<?xml version="1.0"?>
<rule-set name="BusinessRulesSample"
xmlns="http://drools.org/rules"
xmlns:java="http://drools.org/semantics/java"
xmlns:xs
="http://www.w3.org/2001/XMLSchema-instance"
xs:schemaLocation
="http://drools.org/rules rules.xsd
http://drools.org/semantics/java java.xsd">
<!-- Import the Java Objects that we refer
to in our rules -->
<java:import>
java.lang.Object
</java:import>
<java:import>
java.lang.String
</java:import>
<java:import>
net.firstpartners.rp.StockOffer
</java:import>
<!-- A Java (Utility) function we reference
in our rules-->
<java:functions>
public void printStock(
net.firstpartners.rp.StockOffer stock)
{
System.out.println("Name:"
+stock.getStockName()
+" Price: "+stock.getStockPrice()
+" BUY:"
+stock.getRecommendPurchase());
}
</java:functions>
<rule-set>
<!-- Ensure stock price is not too high-->
<rule name="Stock Price Low Enough">
<!-- Params to pass to business rule -->
<parameter identifier="stockOffer">
<class>StockOffer</class>
</parameter>
<!-- Conditions or 'Left Hand Side'
(LHS) that must be met for
business rule to fire -->
<!-- note markup -->
<java:condition>
stockOffer.getRecommendPurchase() == null
</java:condition>
<java:condition>
stockOffer.getStockPrice() < 100
</java:condition>
<!-- What happens when the business
rule is activated -->
<java:consequence>
stockOffer.setRecommendPurchase(
StockOffer.YES);
printStock(stockOffer);
</java:consequence>
</rule>
</rule-set>
This rules file has several interesting parts:
StockOffer
class), one or more conditions that need to be fulfilled, and a
consequence that is carried out if and when the conditions are
met.Having modified and compiled our code, we run the JUnit test simulations again. This time, the business rules are called, our logic evaluates correctly, and our tests pass, as seen in Figure 3. Congratulations--you've just built your first rule-based application!

Figure 3. Successful JUnit test