Financial Calculator and Business Rules
From Kb
Contact Article Author | Blog of Article Author | FirstPartners.net Home | LinkedIn profile of Author
Contents
|
Red Financial Calculator
Go through O’Reilly Rule engine articles to take concepts in here.
Go through sample and ensure it is working as describe
- Note on additional (Spring) integration
- Where to get samples (RP appendix)
- Further Reading & URL’s
- Refer to further section -
- Business bit (in separate file) that we can plug in (refer to other file)
- Conclusion – what you have just done
- Required libs
- Ant build
- Ask Micheal for help
- Go through and remove any fields not being used
- Take in comments from rule engines articles
1.1. How it can be extended
1.2. How it can link to the other samples
To do notes
- Make sure all java / other files have (java) doc
TECH : iNTEGRATE RP calc into workflow and ensure that it works.
- - get CalculatorBean / CalculatorFormBean working with each other
- - get two samples working ok in tomcat
- - move hacky conversions in Calculator Bean (similar to that already done)
- - spring web.xml ????
- - end of ria on rules is (a) excel like web interface
- - additions via script
Introduction
What are rules
- The way the business normally thinks
- writing rules allows the business to review and confirm them
- allows easy change, maintainence and sharing of rules via a rule base
- Deployed into a Rule Engine, can be compiled for
- Link back to what we said in chapter 2, 3 and 4.
This sample
- Shows business rules for a loan calculator
- Shows how easy it is to understand rules (which would be impossible with normal code
- Shows how easy it is to change and maintain rules
More detail of the sample:
- Loan Calculator
- Enter details of the loan
- decides in a simple way
- The amount that can be approved
- Reasons why the loan is approved or declined
- A lot of business knowledge embodied in it
- ’Taking peoples brains and stuffing into a PC
- Say why better than other calcs.
Structure of this chapter
- Sections a-b are business.
- Sections c-d are technical.
- It is done this way so that you can evaluate Red FC first, then decide to take the time to investigate further.
Business
Business walk though of what our sample does
- Applying for loan
- Need to decide to grant it our not
- Gather information / process it / make decision on what to do
- Would normally do this with
- More on the problem
- Complex Business Logic
- Changes half way through the project
- users cannot inspect
- Leads to hard to find bugs
- Advantages for business users
- used to reading specs as spreadsheets
- will probably not update , but ability to ’read’ and inspect code still invaluable.
- Summary of previous two articles
- What are rules engines (business)
- trust the rule engine
Other advantages / problems solved by this approach
- Business user
- Scalability – this scales very well
- Reusability across systems(Rule Repository)
- Furture proofing – systems can change , but the core business knowledge does not have to
- Near Natural language
- Self Documenting
- Can be used from multiple languguages
- Use rule engines as a specificaiton – the fact you can build the rule engine like this , means it can be done (your choice later whether to use use the rule engine version , or to reuse again.)
- Migrating from Legacy : Go through system , document (but the documentation happens to be the same as the ...) . Run your documentation , use it to compare and fine tune results.
- ’The right tool for the job’ – Database to store your data. Web server to display web pages. Rule engine to run your business rules.
Using The Sample : Red Financial Rules
1. Deploy MortgageCalculatorWeb.war (not attached) onto your WebServer. For Tomcat this can be as simple as copying into your local webapps directory.
2. Open the RP Web page in a Browser – this should be something like http:/localhost:8080/MortgageCalculatorWeb/index.jsp
3. Wait a few moments for automatic rule compilcation.
4. Change the Figures – the Mortgage Calculator automatically updates.
- Detail other behaviour with screenshots
Screenshot – Mortgage Calculator
Behind the Scenes
In this section, we are going to see how a simple Excel file can easily be used to manage the business logics of the application. Using one simple Excel file, a lot of the problems in maintaining the business logics are solved. The illustration below to shows how simple it is.
Diagram 1
Screenshot of Rules in Excel Format
In short, we have found an easier way to manage our business logic. Create the Excel file, use a standard Java program , and and deploy anywhere. You have already created a special, loosely-coupled business logic layer for your application. Hence, by the end of the tutorial, you are expected to be able to implement JBoss Rules Engine in your real application.
What is the JBoss Rules Engine?
JBoss Rules Engine (formally known as Drools) allows you to define the rules for your application. What does it mean? It simply means that you can define the business logics or rules of your application in the separate layer. By this, we are reducing the level of independences and the rules can easily be modified and managed by anyone. The most important thing is that the changes in the business logics would have the least impact to the other components of the application.
What we cover in this section
- The end of this sample is being able to run the drools calc via junit /main
- Add recap of what rule engines are & what is jboss rules (refer to previous articles
- Add advanced features (e.g. Write your own rules language)
- make note of the key directories to look at
- Note that while this is from Jboss, it will work in all other app servers and environments, including Tomcat, Oracle, Websphere and Stand Java (no application server)
Using the Red Financial Calculator in your Enterprise
Write in Excel , deploy anywhere with JBoss Rules
’Write in Java , deploy anywhere’ used to be the slogan of Java. What if we could write business logic in an Excel spreadsheet, get the business client to approve it, then deploy anywhere as part of our Java application? This section shows you how to do this using the JBoss rules (Drools) engine to give us scalable yet nimble Enterprise Java applications.
This section will show business users how to write rules , and with a bit of java code, deploy them either as a command line ??? or Web 2 application.
The code samples used here are available online as part of the red-piranha project , freely available under the GPL.
Basic of JBoss Rules Engine
Before looking at the section’s sample, it would be good for you to have a brief look at the JBoss Rules Engine’s basic. How the JBoss Rules Engine works? There are two ways we how JBoss Rules Engine maintaining the business logics. First, we define the rules for our application in the XML files as a repository. Second, use JBoss Rules Decision Table to define all of your rules. I personally preferred the second way as you will see later on, using Excel file to manage the business logics is extremely simple and efficient.
For more details, let me explain each of the way in more details. In the first way, JBoss Rules Engine detects the XML file where all the rules are located, parses it and compiles it into the format that can be understood by the JBoss Rules Engine. In the second way, the Decision Tables is basically converted into a kind of temporary XML file which will be compiled to the format that the JBoss Rules Engine can understand.
Note that while Excel is the storage format, it is only the storage format – other than the one of load data , there is no use of Excel at runtime.
In this section, I am going to show you an alternative technique of JBoss Rules Engine called JBoss Rules Engine Decision Tables. JBoss Rules Engine Decision Tables is created in a simple Excel file and it can either be in the Microsoft Excel or OpenOffice Excel format.
Excel is a good way to manage our business logics or rules because Excel is widely used and most of the people (technical or non-technical people) are familiar on how to utilize it. If your business logics are implemented in the codes there will be so many problems occurred. For example, if the business needs some modification to the business logics, they need to call the Information Technology (IT) people to apply the changes. They will need few hours to explain what changes they want and the IT people may take another few hours time to understand what’s going on. If we have separated the business logics, the non-technical people may easily look at the business logics and apply the modifications necessarily. Well, let’s have a glance on the below illustration on how to produce our first Decision Tables in Excel.
Keywords
There are few special keywords available for our Excel files. It is not hard to understand it. What you need to do is to grab the concept, know how it works and you really are ready to go further.
Give Diagram here , with numbers. Screenshot / click to enlarge. Table to give summary.
- In order to identify the starting of our JBoss Rules Engine Decision Table, we must use the keyword "RuleSet". "RuleSet" occurs only once in our Decision Table. It is mainly used to mark the starting point of our Decision Table. Additionally, you can name your RuleSet with any name that you want just right after the keyword "RuleSet". By specifying the RuleSet, it also means that you have created the initial skeleton of your JBoss Rules Engine Decision Table.
- Besides RuleSet, we have a similar keyword called "RuleTable". Unlike "RuleSet", we are allowed to have more than one "RuleTable" in one Decision Table. "RuleTable" is the place where the rules are defined. Why can we have more than one RuleTable? Simple, your business logics definitely are not simple. You may have various rules for your businesses. This is where the RuleTable is used. Normally, each RuleTable has its own specific functionality. For example, we may have a RuleTable to calculate personal tax, RuleTable to calculate Net Disposable Income (NDI) and etc. By splitting among RuleTable, we have simplified the business logics itself. The collections of "RuleTable" are integrated into one happy "RuleSet".
- Then you may also need to know the keyword "Import". "Import" plays a similar role to the import keyword in Java programming language. You need to import the specific Java class in order for them to be accessible within your JBoss Rules Engine Decision Tables. For example, in order for your business logics to run properly, you definitely need to pass some parameters to the Decision Tables. In most cases, the parameters may be a Java classes. This is where the import keyword is used. You need to import the class / object prior accessing it in the Decision table.
- Next is "Sequential". By specifying the "Sequential" to true, it means that we are forcing the compiler to read our Decision Table from top to bottom. However, we do not really need to specify it as we have already used the rules identification to solve our problem. Do not worry if you are not sure on what the rules identification is about. It will be explained in more depth in the next section. Just keep in your mind that we have a technique called rules identification to solve our problem.
- Now, you need to know the differences between "ACTION" and "CONDITION" as well. These keywords are simple and straight-forward. If you have the condition to be satisfied, you will also have the action to be taken based on which conditions have been satisfied. It is practically similar to the "if then" in Java programming languages.
- if (a == b) {
- System.out.println("a is equal to b");
- }
Look at the Java codes above, we can say that the "if (a == b)" as the CONDITION and the "System.out.println("a is equal to b")" as the ACTION. Within one RuleTable, we can have more than one CONDITION as well as more than one ACTION as it is possible and likely to have more than one if condition and more than one action if the conditions are satisfied.
- Working memory? is a location where all the rules (facts) will be loaded. Here is the concept. How do you actually pass the object / java class so that it is accessible within the JBoss Rules Engine Decision Table? The answer is that the object is asserted into the working memory. Normally, we call those asserted objects as Facts. Then the Decision Table should be able to obtain the object / java class from the working memory for later use. You can also retract it or modify it. Retract means that you are removing the facts from the working memory so the object is no longer accessible within the working memory. Modifying the facts is common and always occurred. You need to remember one thing. If you modify the facts, all the facts will be refreshed and executed again.
So it would be good to have a sample on how to modify the object. An obvious example would be if the condition of "a is equal to b" is satisifed then you need to set "c to be equal as a subtracted by b". In JBoss Rules Engine Decision Table, you have a special command to do that. It is called "modify(object)". Hence, if you have the conditions like below,
- if (a == b) {
- System.out.println("a is equal to b");
- c = a – b;
- }
Then later on, in the ACTION of your JBoss Rules Engine Decision Table, you need to specify "modify(c)" to apply the changes to the object with the name of c. Additionally, if you have completed all the rules in the Decision Table, you can specify the special command called "drools.clearAgenda()" which will subsequently removed all the objects from the working memory and stopping the process of the JBoss Rules Decision Table.
- There are other keywords as well such as "eval" and "var:Type(condition)" which will be explained in more detail in the next section. The reason why it is located in the subsequent section because it would be much clearer and much understandable if you can read it together with the sample of the section. Just a short hints, "eval" is normally used if you would like to check whether two variables are on the same values or not. The best thing about the eval keyword is that it accepts the pure Java codes within the Decision Table. Hence, for the Java-familiar person, using eval is desirable and easy.
Next, we have "var:Type(condition)" or normally we called this Field Constraint. This keyword is used mainly to get the object / Java class from the working memory and assign it to the variable var. Later on, we can deal with the changes to the variable with the name var which is assigned earlier instead of dealing with the object from the working memory directly. This is the standard way of accessing the object in the working memory within Decision Tables.
Regarding the performances, eval will be slower than the var:Type(condition) because eval is not indexed while var:Type(condition) is indexed. Most people who are familiar with Java found that using eval is much easier than using the Field Constraint. However, Field Constraint will be much efficient and faster. You can think of Field Constraint as the SQL language where it tries to specifically define the conditions and thus it is fast. However, the margins of speed are small (in few seconds).
Another hint to improve the performances of our application is to set the "drools.compiler" to use the JANINO compile which is embedded. It is very simple. What you can do is that you can set the System properties (drools.compiler) in java to be JANINO. This is the snippet of codes on how to do it.
System.setProperty("drools.compiler", "JANINO");
You may locate above codes just before you load your Excel file into the JBoss Rules Engine.
Red Financial Calculator
we we implement our first simple JBoss Rules. Well, let’s go to our sample.
Scenario: Consider that we are having a mortgage home loan calculator application. As you know that home loan calculator is normally used by the financial institutions to determine on how much loan can be given to the applicants based on certain applicant’s factors such as occupation, salary, marital status and etc.
For our illustration of the section, we are going to see on how to calculate the Net Disposable Income (NDI) rate. As you know that in most of the home loan calculator, Net Disposable Income (NDI) rate plays an important role in the calculations. Do not worry if you are not sure on what is it used for. Normally, the Net Disposable Income (NDI) rate for each applicant is different based on certain types. Table below illustrates the conditions to determine Net Disposable Income (NDI) rate.
| Combined Pre Tax Annual Income for Applicants | Net Disposable Income (NDI) Rate |
| < 19999 | 0 % |
| < 39999 | 38 % |
| < 49999 | 44 % |
| < 79999 | 48 % |
| < 1000000 | 55 % |
| >= 1000000 | 60 % |
Yes, a simple "if then" in Java should solve the problem. However, that is the main purpose of the JBoss Rules Engine. We are going to store the business logics in the separate layers. By doing that, the application is more maintainable and has loose dependencies. Additionally, by using the JBoss Rules Engine Decision Table, we can allow the non-technical people to modify it as well. Hence, how do we solve it in JBoss Rules Engine especially in the Decision Table?
Go ahead and create a new Excel file. Do not forget to add the RuleSet, Import (if you want to access the Java class from the working memory) and etc. It should look like a below illustration.
Refer to file properly
Above illustration explains that I have created one RuleSet with the name of HomeLoanCalculator. Additionally, I have imported the Calculator as well as the Utility classes so that I can use them within my JBoss Rules Decision Table. Yes, that’s all. That’s all you need to do to start off our JBoss Rules Decision Table. Now, we need to add the RuleTable to calculate the Net Disposable Income (NDI) Rate.
Invoking the Rules Engine
Before we are going any further, it would be good to know on how to invoke the compilation of this JBoss Rules Engine Decision Table from our Java codes. Well, it is simple and everything is available from the JBoss Rules Engine’s API.
Replace this with sample from RP Core – spring table decision loader.
// initialization
RuleBase excelRules = null;
WorkingMemory workingMemory = null;
SpreadsheetCompiler converter = new SpreadsheetCompiler();
String drl = converter.compile(excelPathHere), InputType.XLS );
if (drl != null) {
PackageBuilder builder = new PackageBuilder();
builder.addPackageFromDrl( new StringReader(drl) );
Package pkg = builder.getPackage();
if (pkg != null) {
| // constructing the RuleBase | |||
| excelRules = RuleBaseFactory.newRuleBase(); | |||
| excelRules.addPackage( pkg ); | |||
| } | |||
// creating the working memory
if (workingMemory == null) {
| workingMemory = excelRules.newWorkingMemory(); | ||
| } | ||
else {
| workingMemory.clearAgenda(); | ||
| } | ||
}
Above codes are basically used to convert the Excel file, compile it and create the working memory based on the rules. Additionally, if you are interested, you may try to see what the String drl contains. The drl should contain the rules in the format that JBoss Rules Engine can understand. Okay, we now know how to convert the JBoss Rules Engine’s Decision Table into the working memory. However, all the rules will not be executed at this stage. At this stage, if all the codes are successfully compiled, the rules are ready to be executed. We just need to call the method of fireAllRules() to start executing our defined rules.
Prior executing our rules, I am going to create one simple JavaBean called Calculator to store our Combined Pre Tax Annual Income as well as our Net Disposable Income (NDI) Rate. However, we also need one more attribute called "RulesType" with the type of String. This is what I mean by the rule identification.
What is the use of this rule identification? The answer is simple; it is used to make sure that all our rules are executed correctly and in the correct order. Within one JBoss Rules Engine Decision Table, we may have so many RuleTable. How do we know which rules to be executed first? You may say it is from top to down as we have defined the "Sequential" keyword as true. Well, you are right. However, there is a thing that you need to pay attention. Once one RuleTable is completed and the object is modified, the rules are refreshed and the first rule that we had just executed may be executed again and hence ended in the endless looping. In short, the first rule is executed endlessly. How do we prevent the problem? The answer relies on the "RulesType" attribute that we defined in our JavaBean.
For your better picture, this is how the rule identification works. First, in every RuleTable, we need to check whether the appropriate rule is satisfied or not. We can define it in our CONDITION. If it satisfies the CONDITION, execute the rules and set the next rule to the second rule. We set the first rule to be executed by setting the RulesType attribute into some value i.e. cal.setRulesType("firstRule");. Then when the first rule is executed, we need to modify the cal object to again set the RulesType into the second rule’s command by using the cal.setRulesType("secondRule") and modify(object). By implementing the solution, we have avoided the first rule to be executed endlessly.
So this is my latest Calculator JavaBean.
public class Calculator {
- private String rulesType;
- private double combinedPreTaxAnnualIncome;
- private double ndiMaxPercent;
- public double getCombinedPreTaxAnnualIncome() {
| return combinedPreTaxAnnualIncome; | ||
| } | ||
| public void setCombinedPreTaxAnnualIncome(double val) { | ||
| this.combinedPreTaxAnnualIncome = val; | ||
| } | ||
| public double getNdiMaxPercent() { | ||
| return ndiMaxPercent; | ||
| } | ||
| public void setNdiMaxPercent(double ndiMaxPercent) { | ||
| this.ndiMaxPercent = ndiMaxPercent; | ||
| } | ||
| public String getRulesType() { | ||
| return rulesType; | ||
| } | ||
| public void setRulesType(String rulesType) { | ||
| this.rulesType = rulesType; | ||
| } | ||
}
Okay, now, we are ready to go. Next, we need to add / assert this Calculator Java class into the working memory so that our JBoss Rules Engine Decision Table can access and modify it.
Let’s modify our JBoss Rules Engine Decision Table into something like illustrated below.
There are a lot of interesting things here.
- cal:Calculator(rulesType == "$param") means that we are assigning the object with the type of Calculator (net.tutorial.drools.Calculator) into the variable with the name of cal. Subsequently, we check whether the rulesType of this Calculator bean is equal to the parameter or not. In this case, the parameters are "EXEC-ANNUALINCOME-RULES-2".
- What is the differences between "$param" and $param? Well, if you are comparing or setting some String values, you should use "$param". Unlike "$param", if you are comparing or setting some number values, you may omit the double quote so use $param.
- eval(cal.getCombinedPreTaxAnnualIncome() < $param) means that we are checking the combinedPreTaxAnnualIncome attribute in the variable with the name of cal that has been set previously. Please pay attention to the $param without double quotes.
- Pay attention on how do I define the CONDITION as well as the ACTION.
- Look at the last ACTION where the rulesType are set again for the next rules to be executed and how I used the "modify(object)" command to reflect the changes to the cal variable. Subsequently, I used the drools.clearAgenda() to clear the working memory and mark my Decision Table as completed.
Conclusion
In conclusion, the flow should be something like this. First, it checks whether the rulesType is equal to "EXEC-ANNUALINCOME-RULES-2". If it is satisfied, it checks the CONDITION one by one. If the combinedPreTaxAnnualIncome is less than 19999, the first row is executed and the NdiMaxPercent is 0 and the rulesType is becoming "EXEC-MAX-RULES-1" and stops checking. If the combinedPreTaxAnnualIncome is NOT less than 19999, it goes to the next row and checks whether combinedPreTaxAnnualIncome less than 39999 and so on.
Are we done? Not yet, we have not completed our Java codes yet. Remember that we need to first set some values to the combinedPreTaxAnnualIncome in our Calculator as well as setting the rulesType as "EXEC-ANNUALINCOME-RULES-2" before inserting it into working memory.
So here are my latest Java codes to execute the JBoss Rules Engine Decision Table.
// JavaBean initialization
Calculator cal = new Calculator();
cal.setCombinedPreTaxAnnualIncome(20000);
cal.setRulesType("EXEC-ANNUALINCOME-RULES-2");
// initialization
RuleBase excelRules = null;
WorkingMemory workingMemory = null;
SpreadsheetCompiler converter = new SpreadsheetCompiler();
String drl = converter.compile(excelPathHere), InputType.XLS );
if (drl != null) {
- PackageBuilder builder = new PackageBuilder();
- builder.addPackageFromDrl( new StringReader(drl) );
- Package pkg = builder.getPackage();
- if (pkg != null) {
| // constructing the RuleBase | |||
| excelRules = RuleBaseFactory.newRuleBase(); | |||
| excelRules.addPackage( pkg ); | |||
| } | |||
- // creating the working memory
- if (workingMemory == null) {
| workingMemory = excelRules.newWorkingMemory(); | ||
| } | ||
else {
| workingMemory.clearAgenda(); | ||
| } | ||
- workingMemory.assertObject(cal);
- workingMemory.fireAllRules();
}
System.out.println("NDI Rate is " + cal.getNdiMaxRate());
We need to call workingMemory.fireAllRules() to execute our rules. The assertObject method is used to insert the object into the working memory. The application should print out the appropriate NDI Rate if you have configured everything correctly.
Later on, when you are applying JBoss Rules Engine to your real web application, you may notice that it is quite slow in the beginning. This is basically the compiling time as there might be a lot of rules to be loaded. However, once it is compiled, how JBoss Rules Engine executes the rules is extremely fast and efficient. In my machine, it took less than a second to execute.
Tech Notes
- List out classes used in solution
- Decision table is in war/WEB-INF/File
- Integration with Spring for loading / rp-core (show how we could use this without Spring)
- Note about trick used on Decision tables to get rules firing sequentially
- Perhaps use first sample as simple intro (from Rp-core/test)
- explain a lot of the tricks used in Excel / excel format setup (both on simple and more complicated files)
- Explain load times
- Force a compilation error – e.g. In Test , remove the String "" around the $Param values
- Rule Compilation error The method setOutput(String) in the type SimpleFlowBean is not applicable for the arguments (int)
- Note use of multiple statements per line , modify (cal) to force refiring of rules
- Note how to assign bean to para as part of the decision table
- Note how we use workingmemory – we could have it building up state; in this instance we just re-apply it every time.
- Building up state – e.g. A knowledge base of things it knows to be true
- Allows it to take short-cutss
- Ensure that Eclipse (or other IDE) has /red-financial-calculator/WEB-INF/file on source path , so it can pick up the properties file and decision table
- Picture of Eclipse build
Red Financial Calculator and Web 2.0
- Uses Ajax techniques
- Knowledge capture from users in form of excel spreadsheet
- Excel Spreadsheet but could be google
- Agile testing
- Continuos beta
- Fitnesse
It hurts that Ruby and not Java that is seen as the ’coolest Web 2.0 language’. It hurts even more that Ruby strong points (such as Project Ajax interfaces and Web 2.0 Nimbleness) can be painful for Enterprise Java programmers. In this section , we show that it doesn’t have to be this way if we use frameworks such as Struts , DWR and JBoss rules. We show how to deploy applications with the agility of Ruby , the power of Ajax based web screens , yet still have the performance and scalability of Enterprise Java.
- Business problem
- Familar to Java
- Need more powerful interfaces
- Excel spreadsheets (and problems asscoiated with them)
- Good for rapid response , rich user interface , hard to distrugue
- Web apps
- hard to change
- Ajax and Web 2.0
- What is different about web 2.0
- Alternative Java – Web Frameworks
- Reference to Struts-Ajax section
- Review of Rules Engines
- Summary and links to previous 3 articles (2 by PB, 1 PB-David)
- Where we got to: Command line user interface , but not very exciting for the user!
- Getting started
- Converting Drools to ’conventional’ Web 2.0 project
- Struts
- Overview Diagram (from previous PB section)
- Ant build
- Quick deployment to Ant
- Explain problems with this
- Excel – users are used to rich intereraction
- Figures can be out of date
- Adding DWR to the Mix
- Libs
- Code
- How DWR works
- Architecture
- API
- Calls
- Security
- Testing with Fitnesse
- Summary
- Where we got to
- Other applications for this technique
per
Nowadays, web applications are getting more and more popular. Now the question is how to create your web application more interactive? Well, as you may have realized that the traditional web application constantly refreshes the page whenever it needs to display the information retrieved from the server side codes back to the users. Unfortunately, this may be disturbing especially in cases where you have few combo boxes where a value of the next combo box is dependent on the value chosen in the previous combo box. You may end up in having multiple refreshing of the pages.
Fortunately, AJAX comes to the solution. AJAX is basically using the advantage of JavaScript that runs on client side to be able to call the codes in the server side synchronously.
How to Set Up Struts together with AJAX?
Several alternatives to DWR – do round of of plus and minus of these
Are we also going to use Ruby to carry this out?
Or do we tie this into Fitnesse
We are going to use AJAX DWR - http://getahead.ltd.uk/dwr as well as Struts to enhance our application in the previous section to be more interactive. AJAX DWR is the AJAX specially produced to integrate with Java environment.
Well, assuming that you have your Struts ready, what do we have to to do to include AJAX features? You are required to download the jar libraries for AJAX DWR. There is only one jar file called dwr.jar. You should include this jar file to your web application’s WEB-INF/lib.
There are many people saying that AJAX is actually not compatible with Struts. Well, their views may be right but it does not mean that we do not have any way to utilize AJAX and Struts together. Out of curiosity, why do people claim that AJAX is not compatible with Struts? Simple, Struts has its own FormData as well as Action to manage the flow of the entire application. Consider for our mortgage calculator application in the previous section, if we use Struts, Struts will handle every aspects of our application such as passing the data to and from the JSP, executing business logics and etc. Similarly AJAX is also intended to control the passing of the data to and from JSP. So basically, Struts and AJAX are playing the same responsibility in this case. What can we do? Though we cannot use them together but we can design it in such a way that Struts is used for managing the flow of application among JSP while AJAX is used to manage the passing of data to and from JSP without refreshing the page. Hence, while we still can optimize the use of Struts, we also have the interactive web application delivered by AJAX.
Okay back to our AJAX installation, after putting dwr.jar into our web application’s WEB-INF/lib folder, we need to modify our web.xml to include few entries for AJAX DWR. Please add below codes into your web.xml. Below codes must be in web.xml to ensure that AJAX is working properly. It maps the AJAX’s servlet so that it is accessible from our web application.
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<display-name>DWR Servlet</display-name>
<servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
Additionally, we need to create one more file called dwr.xml within our WEB-INF folder to define the objects that are visible to AJAX. This new xml file defines what classes we can execute from AJAX, what are the available methods, what are the available fields and etc.
For the sample in our previous tutorial, I would define my dwr.xml like below.
<dwr>
| <allow> | ||||
| <convert converter="bean" match="net.tutorial.drools.Calculator"> | ||||
| <param name="include" value="loanSought, termSought, valuationValueOrPurchasePrice, mortgageType, rateType, rateTypeValue, loanToValue, combinedPreTaxAnnualIncome, combinedNetAnnualIncome, combinedNetMonthlyIncome, ndiMaxMinRent, maxAllowableMortgageRepaymentReq, maxAllowableLendingPolicyReq, maxLoadAmountMinRen, maxLoanAmountMultipleIncomeMax, loanAmountWithinCriteria, applicant1, applicant2" /> | ||||
| </convert> | ||||
| <convert converter="bean" match="net.tutorial.drools.Applicant"> | ||||
| <param name="include" value="status, employmentType, occupationType, actualBasicIncome, allowableBasicIncome, actualOvertime, allowableOvertime, actualBonus, allowableBonus, actualCommission, allowableCommission, actualOtherIncome, allowableOtherIncome, preTaxAnnualIncome" /> | ||||
| </convert> | ||||
| <create creator="new" javascript="DroolsLoadConf"> | ||||
| <param name="class" value="net.tutorial.drools.DroolsLoadConf"/> | ||||
| <include method="executeCalculation"/> | ||||
| </create> | ||||
| </allow> | ||||
</dwr>
Do not be afraid if you do not really understand them. They are actually quite simple. It looks rather complicated due to the number of fields that are available to AJAX. The dwr.xml must be started with the <dwr></dwr> tag and followed by <allow></allow>. Next, let’s have a look at the <create> tag. This tag is normally used to make our Java class available within AJAX.
- <create creator="new" javascript="DroolsLoadConf">
Above codes are used to create a new object accessible in AJAX with the name of DroolsLoadConf. It also will create one additional JavaScript file which should be included into the JSP. Within the <create></create> tag, we can specify the <param></param> as well as <include></include> tags. What are they used for?
| <param name="class" value="net.firstpartners.redpiranha.mid.DroolsLoadConf"/> |
<include method="executeCalculation"/>
They are used to define which Java class that the <create></create>should belong by specifying the packages of the Java class. We also need to identify what are the methods in our Java class that are accessible from AJAX. This is where the <include></include> tags are used. They are used to define what methods within the Java class should be available in AJAX. For our case, we have defined a method available from the AJAX which is executeCalculation.
Now, if you look at the codes in Java side, executeCalculation is returning a value back in the form of JavaBean (Calculator). How does AJAX handle it? There is a new tag called <convert></convert> to solve our problem. This tag is basically used to map the object in AJAX with the object in Java programming so that our JavaBean is available within AJAX. Furthermore, we should declare all the fields in our JavaBeans that should be available in AJAX.
| <convert converter="bean" match="net.tutorial.drools.Applicant"> | ||
| <param name="include" value="status, employmentType, occupationType, actualBasicIncome, allowableBasicIncome, actualOvertime, allowableOvertime, actualBonus, allowableBonus, actualCommission, allowableCommission, actualOtherIncome, allowableOtherIncome, preTaxAnnualIncome" /> | ||
| </convert> | ||
Above configurations are basically used to declare a bean derived from net.tutorial.drools.Applicant to be available from AJAX. Additionally this bean has some fields such as status, employmentType, occupationType and so on.
That’s all. We have completed our AJAX configuration. Next, we need to know how to execute them from our JSP page.
What should we add in JSP?
If we have configured everything correctly, DWR AJAX will generate few javascript files. Do you remember that we have created one javascript object so that it is accessible from AJAX using <create></create> tag. DWR AJAX will produce one file for it. In short, if we have five <create> tags; we would also have five javascript files respectively.
- <script src="dwr/interface/DroolsLoadConf.js"></script>
- <script src="dwr/engine.js"></script>
| <script src="dwr/util.js"></script> |
For our tutorial, we are only required to import three javascript files. DroolsLoadConf.js is required because we want DroolsLoadConf to be available from AJAX. For the engine.js and util.js, they are the required files to ensure that our AJAX is running properly.
How do we know that AJAX has completed its processes as it is not even refreshing the page? We can utilize the callback method in determining whether the process has been completed or not. It means that if AJAX has completed its processes (executing server-side codes), it should finally execute the callback method that we have defined previously. Hence, we can put any finishing codes that we would like in this callback method to complete the process.
Subsequently, in our JSP, we can merely call DroolsLoadConf.executeCalculation to execute the server side codes. Now, executeCalculation method accepts one parameter with the type of Calculator. We have already defined Calculator JavaBean by using the <convert></convert> tag. So now, we should be able to pass it easily as illustrated below.
- var cal = new Object();
- cal.rateTypeValue = 10;
- // set all the values here
- DroolsLoadConf.executeCalculation(cal);
We have not completed yet. Where do we define the callback method? Simple, add one more parameter to the executeCalculation which is the name of the callback method. Although in the server side the method only accepts one parameter, AJAX is allowing you to define tow parameters where the latter is used to define the callback method. So you should have something like below.
- DroolsLoadConf.executeCalculation(cal, displayBack);
How does it work? AJAX utilizes the use of the XMLHttpRequest to pass the data to and from the JSP. XMLHttpRequest object will be used to carry the information required and due to its nature, we can get the response back without refreshing the page.
Back to our sample, I will also need to create one more function in my JavaScript to handle the callback method.
function displayBack(calculator) {
- // set back all the results to the JSP
}
That’s all. Yes, that’s all. You have configured AJAX DWR in your J2EE web application successfully.
In order to enhance our application in the previous section, you may think this way. If the user has entered any data or information to one of the textbox, we need to submit them by executing the method which will subsequently execute the JBoss Rules Engine in server side. Then, in the callback method, we need to display the result back to the JSP. By doing so, we will not have to refresh the page to reflect the changes and the users will be able to see the results instantly. Additionally, AJAX is JavaScript and hence, you can combine them with any other JavaScript.
Notes:
Make sure to cover stuff about intitial struts load / subsequent interactions / final submit if required
What Red Financial Calc gives you over the base
- Integration with workflow (without the additional dependencies of Jboss Seam)
- Rule Caching , both as DRL and compiled / serialised Java file. This can reduced startup time by 5-10 minutes.
- Testing ability
- Web Deployment
- Spring Integration
- Explain what this means from a non-technical viewpoint
- Web service (on top of m4)
- Spring Integration in M4
Deployment
1.3. Download as per chapter x
1.4. Build ant file
1.5. Deploy
Where to deploy
- From the command line
- As a web service
- As a Web applications
- Call from Junit / Fit Tests
Technical – Behind the Scenes
1.6. The use we make of the RP Core Files
1.7. Other Frameworks and Libraries used
1.8. Java files
1.9. Configuration Files
- Sample for use in the financial industry
Tech notes
Future Dev: Component for Excel / DRL Management / Save as binary
What items to contribute back to Drools / Jboss rules project?
CalculatorFormBean uses Calculator to store value(nothing special going on here, just makes it easier to convert our previous sample to be Struts aware
- Talk through setting up struts application / use of jsp
- Talk through adding
- Talk through build file & build tasks
- Struts Validation
- Webservice
- T2& T3 talk through 1+ 3 steps
- Calc using drools
- Standard App / Web 2 App /
Now we’re going to show you how to do this ...
- Setting up the Data
- JavaBean
- Rules in Excel
- Setting the Scene
- RuleSet
- Import
- Format of basic table
- Basic Drools Keywords
- Condition
- Action
- Format of Excel
- Dropdowns
- Hide / show
- Colours
- Notes
- Drools conventions used
- Calling this from Java
- Code Snippet
- Times
- Important notes
- Performance
- Data in Memory
- Other Data formats
- .Net and IKVM
- More advanced features
- No Loop
- Salience
- ?? Rule Versioning in a database
- ?? Store rules , like you would other code
- Rule repository (& web based editing)
- Reference to source code
- Plug for later section
- Later on we’ll see how to take this and deploy as Web application
How to Install JBoss Rules Engine?
The installation of JBoss Rules Engine is very simple. Download the JBoss Rules Engine (Drools) from JBoss website - http://www.jboss.com/products/rules. Please use the latest version of 3.0.2 where it is optimized and much faster than previous versions. Create new Java project in your preferred IDE. Extract the zip files and copy all the jar files into your newly created Java project’s build path. I used Eclipse and it looks like the screenshot below in my local machine.
There are four main jar files required by the Drools itself. Additionally, you need to include all the dependencies jar to the build path as well.
That’s all! Yes, that’s all. You have configured the JBoss Rules Engine successfully.
Sequence of Events
1.10. Talk through what is happening behind the scenes during the section ’Using .... in the Enterprise’
Conclusion
1.11. Show that it does what we said it was going to do in
1.12. Link to next sample

