??xml version="1.0" encoding="utf-8" standalone="yes"?>if
...then
statements with a framework that gave us the same benefits of configurability, readability, and reuse that we already enjoy in other areas? This article suggests using the Drools rules engine as a framework to solve the problem.
The sample code below gives a sample of the problem we're trying to avoid. It shows some business logic in a typical Java application.
We've all come across similar (or even more complex) business logic. While this has been the standard way of implementing business logic in Java, there are many problems with it.
J2EE/EJB and "inversion of control" frameworks (such as Spring, Pico, and Avalon) give us the ability to organize our code at a high level. While they are very good at providing reusability, configuration, and security, none of them would replace the "spaghetti code" in the above example. Ideally, whatever framework we choose will be compatible with not only J2EE applications, but also "normal" Java (J2SE--Standard Edition) programs, and most of the widely used presentation and persistence frameworks. Such a framework should allow us to do the following:
An additional problem is that while there are only so many ways to organize web pages and database access, business logic tends to differ widely between applications. Our framework should be able to cope with this and still promote code reuse. Ideally, our application would be "frameworks all the way down." By using frameworks in this way, we can a large amount of our application "out of the box," allowing us to write only the parts that add value for the customer.
How are we going to solve this problem? One solution that is gaining traction is to use a rule engine. Rule engines are frameworks for organizing business logic that allow the developer to concentrate on things that are known to be true, rather than the low-level mechanics of making decisions.
Often, business users are more comfortable with expressing things that they know to be true, than to express things in an if
...then
format. Examples of things that you might hear from a business expert are:
By focusing on what we know to be true, rather than the mechanics of how to express it in Java code, the above statements are clearer than our previous code sample. Still, clear as they may be, we still need a mechanism to apply these rules to the facts that we know and get a decision. Such a mechanism is a rule engine.
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()));
}
}
This is a basic JUnit test, as we know that our (very simple!) system should buy all stocks with a price of less than 100 Euro. Obviously, this won't compile without our data holding class (StockOffer.java) and our business layer class (BusinessLayer.java). These are provided in the following listings.
/** * 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. */ public class BusinessLayer { /** * Evaluate whether or not it is a good idea * to purchase this stock. * @param stockToBuy * @return true if the recommendation is to buy * the stock, false if otherwise */ public static void evaluateStockPurchase (StockOffer stockToBuy){ return false; } }
The StockOffer
class looks like this:
/** * Simple JavaBean to hold StockOffer values. * A 'Stock offer' is an offer (from somebody else) * to sell us a Stock (or Company share). */ public class StockOffer { //constants public final static String YES="YES"; public final static String NO="NO"; //Internal Variables private String stockName =null; private int stockPrice=0; private int stockQuantity=0; private String recommendPurchase = null; /** * @return Returns the stockName. */ public String getStockName() { return stockName; } /** * @param stockName The stockName to set. */ public void setStockName(String stockName) { this.stockName = stockName; } /** * @return Returns the stockPrice. */ public int getStockPrice() { return stockPrice; } /** * @param stockPrice The stockPrice to set. */ public void setStockPrice(int stockPrice) { this.stockPrice = stockPrice; } /** * @return Returns the stockQuantity. */ public int getStockQuantity() { return stockQuantity; } /** * @param stockQuantity to set. */ public void setStockQuantity(int stockQuantity){ this.stockQuantity = stockQuantity; } /** * @return Returns the recommendPurchase. */ public String getRecommendPurchase() { return recommendPurchase; } }
We run BusinessRuleTest
through the JUnit extension of our favorite IDE. If you're not familiar with JUnit, more information can be found at . 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.
Figure 2. JUnit test results
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=
"BusinessRules.drl";
//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(
BusinessLayer.class.getResource(
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
loadRules();
//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
workingMemory.addEventListener(
new DebugWorkingMemoryEventListener());
//Let the rule engine know about the facts
workingMemory.assertObject(stockToBuy);
//Let the rule engine do its stuff!!
workingMemory.fireAllRules();
}
}
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 Object
s) 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
Fresh from building the application, you demonstrate the prototype above to the business users, and they remember a few more rules that they forgot to mention earlier. One of the new rules is that we shouldn't trade stocks where the quantity is a negative number (<0). "No problem," you say, and return to your desk, secure in the knowledge that you can quickly evolve your system.
The first thing you do is to update your simulator, and add the following code to BusinessRuleTest.java:
/**
* Tests the purchase of a stock
* makes sure the system will not accept
* negative numbers.
*/
public void testNegativeStockBuy()
throws Exception{
//Create a Stock with our 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("NO".equals(
testOffer.getRecommendPurchase()));
}
This tests for the new rule described by the business users. If we run this JUnit test, our new test fails, as expected. We need to add a new rule to our .drl file, as follows.
<!-- Ensure that negative prices
are not accepted-->
<rule name="Stock Price Not Negative">
<!-- Parameters we can pass into
the business rule -->
<parameter identifier="stockOffer">
<class>StockOffer</class>
</parameter>
<!-- Conditions or 'Left Hand Side' (LHS)
that must be met for rule to fire -->
<java:condition>
stockOffer.getStockPrice() < 0
</java:condition>
<!-- What happens when the business rule
is activated -->
<java:consequence>
stockOffer.setRecommendPurchase(
StockOffer.NO);
printStock(stockOffer);
</java:consequence>
</rule>
This rule is similar in format to the previous one, expect that our <java:condition>
is different (testing for negative numbers) and the <java:consequence>
sets the recommend purchase to No
. We run our unit tests/simulator again, and this time the test passes.
At this point, if you're used to procedural programming (like most Java programmers), you may be scratching your head: here we have a file containing two separate business rules, yet we haven't told the rule engine which is more important. However, our stock price (of -22) satisfies both rules (i.e., it is less than 0 and it is less than 100). Despite this, we get the correct result, even if we swap the order of the rules around. How does this work?
The extract of the console output below helps us to see what is going on. We see that both rules are firing (the [activationfired]
line), and that the Recommend Buy
is first set to Yes
and then to No
. How does Drools know to fire these rules in the correct order? If you look at the Stock Price Low Enough
rule, you will see that one of the conditions is that recommendPurchase()
is null. This is enough for the Drools rule engine to decide that the Stock Price Low Enough
rule should be fired before the Stock Price Not Negative
rule. This process is called conflict resolution.
FIRE RULES
----------
[ConditionTested: rule=Stock Price Not Negative;
condition=[Condition: stockOffer.getStockPrice()
< 0]; passed=true; tuple={[]}]
[ActivationCreated: rule=Stock Price Not Negative;
tuple={[]}]
[ObjectAsserted: handle=[fid:2];
object=net.firstpartners.rp.StockOffer@16546ef]
[ActivationFired: rule=Stock Price Low Enough;
tuple={[]}]
[ActivationFired: rule=Stock Price Not Negative;
tuple={[]}]
Name:MEGACORP Price: -22 BUY:YES
Name:MEGACORP Price: -22 BUY:NO
If you're a procedural programmer, no matter how clever you think this is, you still may not trust it completely. That is why we have our unit tests/simulator: "hard" JUnit tests (using normal Java code) ensure that the rule engine makes its decisions along the lines we want it to. (And doesn't spend billions on worthless stock!) At the same time, the power and the flexibility of our rule engine allows us to quickly develop the business logic.
Later on, we will see more sophisticated forms of conflict resolution.
Now the folks on the business side are really impressed and are starting to think through the possible options. They've come across a problem with stocks of XYZ Corp and have decided to implement a new rule: Only buy stocks of XYZ Corp if they are less than 10 Euro.
As before, you add the test to our simulator and include the new business rule in our rules file, as per the following listings. First, we add a new method to BusinessRuleTest.java:
/**
* Makes sure the system will buy stocks
* of XYZ corp only if it really cheap
*/
public void testXYZStockBuy() throws Exception{
//Create a Stock with our simulated values
StockOffer testOfferLow = new StockOffer();
StockOffer testOfferHigh = new StockOffer();
testOfferLow.setStockName("XYZ");
testOfferLow.setStockPrice(9);
testOfferLow.setStockQuantity(1000);
testOfferHigh.setStockName("XYZ");
testOfferHigh.setStockPrice(11);
testOfferHigh.setStockQuantity(1000);
//Run the rules on it and test
BusinessLayer.evaluateStockPurchase(
testOfferLow);
assertTrue("YES".equals(
testOfferLow.getRecommendPurchase()));
BusinessLayer.evaluateStockPurchase(
testOfferHigh);
assertTrue("NO".equals(
testOfferHigh.getRecommendPurchase()));
}
Next, we need a new <rule>
in BusinessRules.drl:
<rule name="XYZCorp" salience="-1">
<!-- Parameters we pass to rule -->
<parameter identifier="stockOffer">
<class>StockOffer</class>
</parameter>
<java:condition>
stockOffer.getStockName().equals("XYZ")
</java:condition>
<java:condition>
stockOffer.getRecommendPurchase() == null
</java:condition>
<java:condition>
stockOffer.getStockPrice() > 10
</java:condition>
<!-- What happens when the business
rule is activated -->
<java:consequence>
stockOffer.setRecommendPurchase(
StockOffer.NO);
printStock(stockOffer);
</java:consequence>
</rule>
Note that in the business rules file, after the rule name, we set our salience
to -1
(i.e., the lowest priority of all of the rules we have specified so far). Most of the rules in our system conflict, meaning Drools must make some decision on the order in which to fire rules, given that the conditions for all of the rules will be met. The default way of deciding is:
Salience
: A value we assign, as per the above listing.
Recency
: How many times we have used a rule.
Complexity
: Specific rules with more complicated values fire first.
LoadOrder
: The order in which rules are loaded. If we did not specify the saliency of our rule in this example, what would happen is:
Recommend Buy
flag would be set to No
).
Recommended Buy
flag to yes
. This would give a result that we don't want. However, since our example does set the saliency factor, the test and our business rules work as expected.
While most of the time, writing clear rules and setting the saliency will give enough information to Drools for it to choose the proper order in which to fire rules, sometimes we want to change the entire manner in which rule conflicts are resolved. An example of how to change this is given below, where we tell the rule engine to fire the simplest rules first. A word of warning: be careful when changing conflict resolution, as it can fundamentally change the behavior of the rule engine--a lot of problems can be solved first with clear and well-written rules.
//Generate our list of conflict resolvers
ConflictResolver[] conflictResolvers =
new ConflictResolver[] {
SalienceConflictResolver.getInstance(),
RecencyConflictResolver.getInstance(),
SimplicityConflictResolver.getInstance(),
LoadOrderConflictResolver.getInstance()
};
//Wrap this up into one composite resolver
CompositeConflictResolver resolver =
new CompositeConflictResolver(
conflictResolvers);
//Specify this resolver when we load the rules
businessRules = RuleBaseLoader.loadFromUrl(
BusinessLayer.class.getResource(
BUSINESS_RULE_FILE),resolver);
For our simple application, driven by JUnit tests, we don't need to alter the way the Drools resolves rule conflicts. It is useful to know how conflict resolution works, especially when your application grows to meet more complex and demanding requirements.
This article demonstrated a problem that most programmers have had to face: how to put some order on the complexity of business logic. We demonstrated a simple application using Drools as a solution and introduced the notion of rule-based programming, including how these rules are resolved at runtime. Later on, a follow-up article will take these foundations and show how to use them in an enterprise Java application.
Paul Browne , based in Dublin, Ireland, has been consulting in enterprise Java with FirstPartners.net for almost seven years.
These days enterprise Java could almost put you to sleep. How many hundreds of J2EE-EJB web applications have been written that capture information from a web page and store it in a database? What really keeps developers awake at night is trying to write and maintain the complex business logic in their applications. This is a problem not only for new applications, but increasingly, for long-lived, business-critical apps whose internal logic needs to change frequently, often at very short notice.
In an earlier article, "Give Your Business Logic a Framework with Drools," I introduced the Drools framework and showed how it could be used to organize complicated business logic. Drools replaced many tangled if ... then
statements with a simple set of things known to be true. If you are ever in a meeting with business customers, and your head hurts with the complexity of what they want you to implement, then maybe you should consider a rule engine such as Drools. This article will show you how you can do this in an enterprise Java application.
Most enterprise Java developers already have their favorite frameworks. In no particular order, these include presentation frameworks (Struts, JSF, Cocoon, and Spring), persistence frameworks (JDO, Hibernate, Cayenne, and Entity Beans) and structural frameworks (EJB, Spring again, Pico, and Excalibur), as well as many others. Each framework does one very useful thing (or more), and gives developers a lot of instant "out of the box" functionality. Deploying an application using frameworks means you avoid a lot of the boring bits and concentrate on what is really needed.
Until now, there was a gap in what the frameworks were able to do, in that business logic had no framework. Tools like EJB and Spring are good, but have little to say about how to organize your if ... then
statements! Adding Drools to your developer toolbox means that it is now possible to build an application with "frameworks all the way down." Figure 1 shows a diagram of such an application.
Figure 1. Frameworks for Java applications
This article will build on what we already know of the Drools framework and allow us to build such an application.
It's almost a cliche in software engineering to say that "if you have a hammer, everything looks like a nail." While rule engines can solve a lot of problems for us, it is worth considering whether a rule engine is really appropriate for our enterprise Java application. Some questions to ask are:
If you're writing an enterprise application, chances are that it will need to scale to hundreds, if not thousands, of users. You know that existing Java and J2EE applications can do this, but how will a application using Drools cope with this pressure? The answer is "surprisingly well." While most developers hate to "lose control" and rely on other people's code (i.e., a framework), consider the points below--not only should your application be as fast as "traditional" coding methods, but Drools may even make your application run faster:
if ... then
statements with an optimized network. It is important to note that the Rete algorithm involves a tradeoff between using more memory to reduce delays at run time. While this isn't a factor in most modern servers, we wouldn't yet recommend deploying Drools on your mobile phone! Most enterprise Java applications are accessed using a web interface, and one of the most widely adopted web-presentation frameworks is Struts, from Apache. Ideally, we'll write our application so that the presentation layer knows about the business layer underneath, but not the other way around. This has the advantage not only of allowing us to change the presentation framework at a later date (e.g., to an Ajax or web service interface), but also means the code examples give should be readily applicable to other web frameworks like Spring.
The following code snippet demonstrates how to call the business logic tier (using the rule engine) from the web presentation layer. The code uses the results to decide which page to display. In this sample, we use a Struts action, but the code is similar for any other web framework or even a servlet or a JSP page. This snippet works with a supporting struts-config.xml, JSP pages to post/display data, and a way of generating the WAR file for deployment. The snippet shows how to integrate the rule engine with the web framework.
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import BusinessLayer;
/**
* Sample Struts action with Pseudocode
*/
public class SampleStrutsAction extends Action{
/**
* Standard Struts doPerfom method
*/
public ActionForward doPerform(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws InvalidEntryPointException {
//Local Variables
StockOffer userOffer =null;
//Get any previous values from the session
userOffer=(StockOffer)request.getSession()
.getAttribute("PREVIOUS_STOCK_OFFER");
//create this object if it is null
if (null==userOffer){
userOffer = new StockOffer();
}
//Update with the incoming values
//These values match those on the form
userOffer.setStockName(request.
getParameterValue("STOCK_NAME"));
userOffer.setStockPrice(request
.getParameterValue("STOCK_PRICE"));
userOffer.setStockQuantity(request
.getParameterValue("STOCK_QTY"));
//Reset the output value
userOffer.setRecommendPurchase(null);
//Call the Business Layer
BusinessLayer
.evaluateStockPurchase(userOffer);
//Forward to the appropriate page
if ("YES".equals(
testOffer.getRecommendPurchase()){
return mapping.findForward("YES_WEB_PAGE");
}
//otherwise default to the no page
return mapping.findForward("NO_WEB_PAGE");
}
}
There are a couple of things going on this sample. Often, we build up the data we need from the user over several web pages, so this sample shows how we can achieve this by retrieving the StockOffer
object that we have previously stored in the web server session. Next, we update the StockOffer
with any values that the user may have changed on the web page. We then reset the recommendPurchase
flag to clear any previous results before we call the business logic layer. Finally, we take the response of the business logic and use it to decide which page to forward the user to.
In this example, note how we split the business logic (yes/no on whether or not to buy a stock) from the presentation logic (decide which page to go to). This allows us to reuse our business rules across several different applications In addition, take look at how the state information (i.e., things that the user has already told us) is stored in the StockOffer
object/web server session, and not in the business layer. By keeping the business layer stateless in this way, we make the entire application much more scalable and performant.
So far, our application has a web presentation layer and a rules engine for the business layer, but no means of getting data to and from a database. This section gives an example of how to do this. We base our example on the Data Access Object (DAO) pattern, where we encapsulate all code that "talks" to the database (or back-end data source) in one pluggable, configurable class. As such, the example is applicable to other persistence frameworks, such as Hibernate and Cayenne.
Some important points about the way we want to organize the data layer are:
To implement our simple Data Access Object, we create three new objects: StockNameDao
, DaoImplementation
, and DaoFactory
.
StockNameDao
is an interface that defines two methods: getStockNames()
returns a list of the stock names that we deal with, and isOnStockList()
checks that a given stock is on the list of stocks that we deal with. Our business layer will call these methods as and when it needs the information.
DaoImplementation
is an actual implementation of StockNameDao
. In this case the values are hard-coded, but we could have queried a database or accessed an information system like Bloomberg via a web service.
DaoFactory
is what we use to create an appropriate instance of StockNameDao
. The advantage this approach has over creating the class directly is that it allows us to configure what DAO implementation we use at runtime (frameworks like Spring are especially good at this). One factory can return many types of DAOs (e.g., StockNameDao
, StockPriceDao
, StockHistoryDao
), which means we can pass in our DaoFactory
, and let the individual rules decide on the data and DAOs that they require.
Here's what the StockNameDao
interface looks like:
/**
* Defines a Data Access Object - a non data
* source specific way of obtaining data.
*/
public interface StockNameDao {
/**
* Get a list of stock names for the application
* @return String[] array of stock names
*/
public String [] getStockNames();
/**
* Check if our stock is on the list
* @param stockName
* @return
*/
public boolean isOnStockList(String stockName);
}
And here's the DaoImplementation
:
/**
* Concrete Definition of a Data Access Object
*/
public class DaoImplementation
implements StockNameDao {
/**
* Constructor with package level access only
* to encourage use of factory method
*
*/
DaoImplementation(){}
/**
* Get a list of stock names for the app.
* This is a hard coded sample
* normally we would get this from
* a database or other datasource.
* @return String[] array of stock names
*/
public String[] getStockNames() {
String[] stockNames=
{"XYZ","ABC","MEGACORP","SOMEOTHERCOMPANY"};
return stockNames;
}
/**
* Check if our stock is on the list
* @param stockName
* @return true / false as appropriate
*/
public boolean isOnStockList(String stockName){
//Get our list of stocks
String stockList[] = getStockNames();
//Loop and see if our stock is on it
// done this way for clarity . not speed!
for (int a=0; a<stockList.length;a++){
if(stockList[a].equals(stockName)){
return true;
}
}
//Default return value
return false;
}
}
The simple DaoFactory
just returns a DaoImplementation
:
package net.firstpartners.rp;
/**
* Factory Method to get the Data Access Object.
* Normally we could replace this with a
* framework like Spring or Hibernate
*/
public class DaoFactory {
/**
* Get the stock name Dao
* This sample is hardcoded - in reality
* we would make this configurable / cache
* instances of the Dao as appropriate
* @return an instance of StockNameDao
*/
public static StockNameDao getStockDao(){
return new DaoImplementation();
}
}
Now that we have our simple DAO implementation to serve as our database layer, how do we integrate it with the Drools business layer? The updated business rules file, BusinessLayer.xml, shows us how.
<?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>
<java:import>
net.firstpartners.rp.DaoFactory
</java:import>
<java:import>
net.firstpartners.rp.StockNameDao
</java:import>
<!-- Application Data not associated -->
<!-- with any particular rule -->
<!-- In this case it's our factory -->
<!-- object which gives us back -->
<!-- a handle to whatever Dao (Data -->
<!-- access object) that we need -->
<application-data
identifier="daoFactory">DaoFactory
</application-data>
<!-- 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>
<!-- Check for XYZ Corp-->
<rule name="XYZCorp" salience="-1">
<!-- Parameters we can pass into-->
<!-- the business rule -->
<parameter identifier="stockOffer">
<class>StockOffer</class>
</parameter">
<!-- Conditions that must be met for -->
<!-- business rule to fire -->
<java:condition>
stockOffer.getStockName().equals("XYZ")
</java:condition>
<java:condition>
stockOffer.getRecommendPurchase() == null
</java:condition>
<java:condition>
stockOffer.getStockPrice() > 10
</java:condition>
<!-- What happens when the business -->
<!-- rule is activated -->
<java:consequence>
stockOffer.setRecommendPurchase(
StockOffer.NO);
printStock(stockOffer);
</java:consequence>
</rule>
<!-- Ensure that negative prices -->
<!-- are not accepted -->
<rule name="Stock Price Not Negative">
<!-- Parameters we can pass into the -->
<!-- business rule -->
<parameter identifier="stockOffer">
<class>StockOffer</class>
</parameter>
<!-- Conditions for rule to fire -->
<java:condition>
stockOffer.getStockPrice() < 0
</java:condition>
<!--When rule is activated then ... -->
<java:consequence>
stockOffer.setRecommendPurchase
(StockOffer.NO);
printStock(stockOffer);
</java:consequence>
</rule>
<!-- Check for Negative Prices-->
<rule name="Stock Price Low Enough">
<!-- Parameters for the rule -->
<parameter identifier="stockOffer">
<class>StockOffer</class>
</parameter>
<!-- Now uses Dao to get stock list -->
<java:condition>
daoFactory.getStockDao().isOnStockList(
stockOffer.getStockName())
</java:condition>
<java:condition>
stockOffer.getRecommendPurchase() == null
</java:condition>
<java:condition>
stockOffer.getStockPrice() < 100
</java:condition>
<!-- When rule is activated do this -->
<java:consequence>
stockOffer.setRecommendPurchase(
StockOffer.YES);
printStock(stockOffer);
</java:consequence>
</rule>
</rule-set>
There are several changes to this file to integrate the data access layer with our business rules:
<java:import>
statements to reference the StockNameDao
, DaoImplementation
, and DaoFactory
classes that we added to the system.
<application-data>
, which assigns an instance of the DaoFactory
class to a variable. <application-data>
tags are similar to parameters, except they apply to all business rules, and not just one.
Stock Price Low Enough
rule has a new condition, which uses the DaoFactory
and StockNameDao
to check if the stock is on the list of those that we deal with. We run our BusinessRulesTest
(simulator) again. The simulator/unit tests run OK, since even though we have changed the structure of the program, we haven't (yet) changed what it does. From looking at the output logs, we can see that our business rules are using StockNameDao
as part of their evaluations, and that DaoImplementation.isOnStockList()
is being called.
While this example shows the reading of information from a data source, the principles are the same for writing information, if that is what a rule has decided should be done. The differences would be that our DAO would have a setSomeInformation()
method, and that the method would be called in the <java:consequence>
part of the business rule, once the specific conditions had been met.
In this article, we showed that most Java server applications have three tiers: presentation, business logic, and data persistence. While the use of frameworks is widely accepted in the presentation and persistence layers, until now no framework has been available to encapsulate low-level business logic. As we've seen in the examples, Drools and JSR-94 are ideal candidates for reducing the complexity and speeding the development of Java applications. I hope that these examples inspire you to take a closer look at rule engines, and that they save many hours of development and maintenance time in your applications.
Paul Browne , based in Dublin, Ireland, has been consulting in enterprise Java with FirstPartners.net for almost seven years.
支持BI的开源工h量众多,但是大多数的工具都是偏重某方面的。例如,CloverETL偏重ETLQJPivot偏重多维分析展现QMondrian是OLAP服务器。而Bee、Pentaho和SpagoBI{项目则针对商务问题提供了完整的解决Ҏ?/font>
ETL 工具
ETL开源工具主要包括CloverETL和Octupus{?
Q?QCloverETL是一个Java的ETL框架Q用来{换结构化的数据,支持多种字符集之间的转换Q如ASCII、UTF-8和ISO-8859-1{)Q支持JDBCQ同时支持dBase和FoxPro数据文gQ支持基于XML的{换描q?
(2)Octupus是一个基于Java的ETL工具Q它也支持JDBC数据源和ZXML的{换定义。Octupus提供通用的方法进行数据{换,用户可以通过实现转换接口或者用Jscript代码来定义{换流E?
OLAP服务?
(1)Lemur主要面向HOLAPQ虽焉用C++~写Q但是可以被其他语言的程序所调用。Lemur支持基本的操作,如切片、切块和旋{{基本操作?
(2)Mondrian面向ROLAP包含4层:表示层、计层、聚集层、存储层?
?表示层:指最l呈现在用户昄器上的以及与用户之间的交互,有许多方法来展现多维数据Q包括数据透视表、饼、柱、线状图?
?计算层:分析、验证、执行MDX查询?
?聚集层:一个聚集指内存中一l计?cell)Q这些值通过l列来限制。计层发送单元请求,如果h不在~存中,或者不能通过旋{聚集导出的话Q那么聚集层向存储层发送请求。聚合层是一个数据缓冲层Q从数据库来的单元数据,聚合后提供给计算层。聚合层的主要作用是提高pȝ的性能?
?存储层:提供聚集单元数据和维表的成员。包括三U需要存储的数据Q分别是事实数据、聚集和l?
OLAP客户?
JPivot是JSP风格的标{ֺQ用来支持OLAP表,使用户可以执行典型的OLAP操作Q如切片、切块、上钅R下ȝ。JPivot使用Mondrian服务器,分析l果可以导出为Excel或PDF文g格式?
数据库管理系l?
主要的开源工具包括MonetDB、MySQL、MaxDB和PostgreSQL{。这些数据库都被设计用来支持BI环境。MySQL、MaxDB和PostgreSQL均支持单向的数据复制。BizGres目的目的在于PostgreSQL成ؓ数据仓库?BI的开源标准。BizGres为BI环境构徏专用的完整数据库q_?
完整的BI开源解x?
1.Pentaho 公司的Pentaho BI q_
它是一个以程Z心的、面向解x案的框架Q具有商务智能组件。BI q_是以程Z心的Q其中枢控制器是一个工作流引擎。工作流引擎使用程定义来定义在 BI q_上执行的商务程。流E可以很Ҏ被定Ӟ也可以添加新的流E。BI q_包含lg和报表,用以分析q些程的性能。BI q_是面向解x案的Q^台的操作是定义在程定义和指定每个活动的 action 文档里。这些流E和操作共同定义了一个商务智能问题的解决Ҏ。这?BI 解决Ҏ可以很容易地集成到^台外部的商业程。一个解x案的定义可以包含L数量的流E和操作?
BIq_包括一?BI 框架、BI lg、一?BI 工作台和桌面收g。BI 工作台是一套设计和理工具Q集成到Eclipse环境。这些工具允许商业分析h员或开发h员创建报表、A表盘、分析模型、商业规则和 BI 程。Pentaho BI q_构徏于服务器、引擎和lg的基之上Q包括J2EE 服务器、安全与权限控制、portal、工作流、规则引擎、图表、协作、内容管理、数据集成、多l分析和pȝ建模{功能。这些组件的大部分是Z标准的,可用其他品替换之?
2.ObjectWeb
该项目近日发布了SpagoBi 1.8版本。SpagoBi 是一Ƒ֟于Mondrain+JProvit的BIҎQ能够通过OpenLaszlo产生实时报表Qؓ商务目提供了一个完整开源的解决ҎQ它늛了一个BIpȝ所有方面的功能Q包括:数据挖掘、查询、分析、报告、Dashboard仪表板等{。SpagoBI使用核心pȝ与功能模块集成的架构Q这样在保q_E_性与协调性的基础上又保证了系l具有很强的扩展能力。用h需使用SpagoBI的所有模块,而是可以只利用其中的一些模块?
SpagoBI使用了许多已有的开源YӞ如Spago和Spagosi{。因此,SpagoBI集成?Spago的特征和技术特点,使用它们理商务对象Q如报表、OLAP分析、A表盘、记分卡以及数据挖掘模型{。SpagoBI支持BIpȝ的监控管理,包括商务对象的控制、校验、认证和分配程。SpagoBI采用Portalet技术将所有的BI对象发布到终端用P因此BI对象可以集成到为特定的企业需求而已l选择好的Portalpȝ中去?
3.Bee目
该项目是一套支持商务智能项目实施的工具套gQ包括ETL工具和OLAP 服务器。Bee的ETL工具使用ZPerl的BEIQ通过界面描述程Q以XML形式q行存储。用户必d转换q程q行~码。Bee的ROLAP 服务器保证多通SQL 生成和强有力的高速缓存管?使用MySQL数据库管理系l?。ROLAP服务器通过SOAP应用接口提供丰富的客户应用。Web Portal作ؓ主要的用h口,通过Web览器进行报表设计、展C和理控制Q分析结果可以以Excel、PDF、PNG、PowerPoint?text和XML{多UŞ式导出?
Bee目的特点在于:
?单快L数据讉KQ?
?支持预先定义报表和实时查询;
?通过拖拽方式L实现报表定制Q?
?完整报表的轻松控Ӟ
?以表和图q行高质量的数据展示?/p>
l过2005q的强劲发展Q中国商业智能(BIQY件市场销售额辑ֈ10.15亿元人民币,q增长率辑ֈ54.96Q?006q_随着履行加入WTO全面开攑ָ场承诺时间的临近和中国企业国际化的步伐加快以及政府职能的全面转变Q中国金融、电信、政府、零售、制造等行业对商业智能技术应用的需求全面爆发。赛q顾问预?006q中国BI软g市场规模超q?6亿元人民?见图1)?
国内商业软g市场呈现十大发展趋ѝ?
势一:融合多种技术的集成产品出现?
2006qBI产品技术的发展势是:q有的初步应用如报表分析、数据集成,向深度和q度应用发展Q数据仓库徏模和数据挖掘{技术的应用实质性推开?
2006q的BI产品把数据仓库建模以及数据挖掘{技术实质性地应用q来。同时BI技术将与ERP、CRM、企业门L技术相融合QŞ成集成化的品。尤其在面向中小企业用户的企业管理Y件方案中QERP、CRM厂商会将BIҎ嵌入到自qERP或CRMpȝ中。而整合了企业门户的BI产品Q在Z~少旉、必d注意力放在真正重要的决策规则上的q代Q可以减作决策时必d析的数据量?
势?BI产品的整体h格在逐步下降?
在h格方面,BI软g一直处于高端h位,提供l信息化“贵族”用。而以中小企业Z表的中、低端客P也希望花上几十万可以上一套BI软g。因此无论是国际BI厂商q是国内BI企业都针寚w、中、低端用户呈现出不同的h格策略,M价位呈现下降势。这为国内更q大的企业应用BI产品提供了可能?
势?高端市场归属国际Q中低端落户国内?
中国的BI市场从开始就l历了一个激烈竞争的时期Q高端市国际大厂商所占据Q低端市场是国内的BI厂商及行业的ISV及集成商在竞争?006q中国的BI市场可能在低端市场初步出现像用友、金蝶在财务套装软g那样的格局Q几个大的国内BI厂商凭借本地化和销售网l占据市?0Q以上的市场份额。而在大的行业市场里,BI会与解x案融合在一P市场被行业的ISV所把持?
势?在营销{略上,整合营销势凸显?
2006qBI厂商面临激烈而现实的市场竞争。营销手段、品研发受到前所未有的重视。更多的软文宣传、研讨会Q包括行业研讨会Q、新品发布会、E讲以及联合、ƈ购等会?006q中国BI市场里上演。多U多L营销方式让人目不暇接?
势?用户重视效益Q关注BPM?
用户之所以投入巨额资金购买BI软gQ目的都是希望对q营数据q行分析Q以实现实时响应。对于企业来Ԍq希望BI能够支持企业程优化以及提高生力。当然其最l目标都是向_理要效益。但是目前的很多l织q没有徏立胦务标准来衡量此项IT投入的效益。ؓ此,BI技术和l效理结合而Ş成的BPM (企业l效理)成ؓBI领域用户的关注点。在应用领域斚wQBPM可以深入特定的业务流E或功能Q在功能划分斚wQBPM可按企业业务功能划分Q如财务l效理、客户关pȝW效管理、生产运营W效管理、交叉业务W效管理;在系l构造方面,BPM能够协调业务zd以达到特定的l果Q如~制预算、评估关键供应商{。因此,BI软g供应商在用BI技术提升企业W效上面做文章Q一定会辑ֈ一定的用户满意度。 ?/font>
势?以品ؓ依托Q增值服务成主角?
目前BI软g领域中的多数软g供应商,其Y件授权收入和服务收入基本持^Q但随着数据仓库和查询、报表工兯Y件的应用普及Q下一步如何开展分析型应用成Z|从销售品中可获得的收入逐渐降低。此消彼长,帮助用户建立分析和挖掘模型等应用解决Ҏ和咨询服务的收入在明年上升Q最l将过软g产品授权收入。因此,如何在提供增值服务这C轮的较量中胜出,是BI软g供应商现在需要未雨绸~的。 ?br />
势?应用范围不断扩展Q区域边界日模p?
目前Q华北、华东和华南地区BI软g占据了绝大部分的市场份额Q而其它四地区的市Z额相对偏低。但华北、华东、华南地区由于电信、金融、政府等行业信息化水q高,U篏了大量数据,渴望从这些数据中LQ因此,2006q内仍是BI软g的主要应用领域。但随着BI软g应用范围的不断扩大和用户认知度的提升Q各BI软g供应商将致力于开拓其它区域的市场。另?006q国家的“西部大开发”和“振兴东北老工业基地”两大战略的深入推进和实施,促q西部和东北地区对于交通、能源、电信、电子政务的Q这在一定程度上带动襉K和东北地区对于BI软g产品及应用的需求,从而ؓBI软g的推q和应用带来新的发展机遇。(见图2Q?/font>
势?中小企业的BI应用市场份额逐渐扩大?
虽然在垂直市ZQ大型企业依然是BI的应用主体,但是中小企业的BI应用需求开始释放?
中小企业来注重自w徏设,已经意识C息化的重要性和q切性。因此,国内q大的中企业逐渐呈现对管理Y件旺盛的需求态势Q必成?006q国?BI市场重要l成部分。国际一的BI厂商BO公司和国内BI领域g者菲奈特公司已经开发出适合中小企业应用的BI解决Ҏ?
赛_N预计2006q国内中企业对BI的应用需求将快速增长,市场份额由2005q的32.7%上升?2.5%Q成为BI市场上新的增长亮炏V(见图3Q?/font>
势?优势行业C不减Q行业集成和解决Ҏ成ؓL?
从行业应用来看,中国的金融业、电信业?006q仍占据着BI应用的优势行业地位。另外政府和消费品制造业及零售业(如百货企业及q锁企业)对BI的需求也不容忽视。由于BI的分析型应用在未来占主导地位,每个行业又都需要不同的行业知识Q因此电信及金融的BI业务会被行业的集成及ISV占据一定的市场份额。(见图4Q?/font>