| Sign In/My Account | View Cart |
Give Your Business Logic a Framework with Drools
Pages: 1, 2, 3, 4, 5, 6, 7
JSR
94, the javax.rules API, sets a common standard for interacting
with rule engines, much as JDBC allows us to interact with varying
databases. What JSR-94 does not specify is how the actual rules are
written, leaving plenty of choice among the most widely used Java
rule engines:
Imagine this scenario: minutes after reading this article, your boss asks your to prototype a stock trading application. As the business users still haven't fully defined the business logic, you think it a good idea to implement it using a rules engine. The final system will be accessible over an intranet and will need to communicate with back-end database and messaging systems. To get started, download the Drools framework (with dependencies). Create a new project in your favorite IDE and make sure all of the .jars are referenced in it, as per Figure 1. This screenshot is Eclipse-based, but the setup will be similar for other IDEs.

Figure 1. Libraries needed to run Drools
Due to the huge potential losses if our stock trading system went amok, it's vital that we have some sort of simulator to put our system through its paces. Such a simulator also gives you confidence that the decisions made by the system are those that are intended, even after rule changes are made. We'll borrow some tools from the Agile toolbox and use JUnit as a framework for our simulations.
The first code we write is the JUnit Test/simulator, as per the
following listing. Even if we can't test every combination of
values likely to be input into our application, some tests are
better than none at all. In this example, all of our files and classes
(including unit tests) are in one folder/package, but in reality,
you would implement a proper package and folder structure. We'd
also use Log4j instead of the System.out calls in the
sample code.
import junit.framework.TestCase;
/*
* JUnit test for the business rules in the
* application.
*
* This also acts a 'simulator' for the business
* rules - allowing us to specify the inputs,
* examine the outputs and see if they match our
* expectations before letting the code loose in
* the real world.
*/
public class BusinessRuleTest extends TestCase {
/**
* Tests the purchase of a stock
*/
public void testStockBuy() throws Exception{
//Create a Stock with simulated values
StockOffer testOffer = new StockOffer();
testOffer.setStockName("MEGACORP");
testOffer.setStockPrice(22);
testOffer.setStockQuantity(1000);
//Run the rules on it
BusinessLayer.evaluateStockPurchase(testOffer);
//Is it what we expected?
assertTrue(
testOffer.getRecommendPurchase()!=null);
assertTrue("YES".equals(
testOffer.getRecommendPurchase()));
}
}