Jan 232013
 

For the past few years I have been designing and building web services which make use of decision management technology such as Drools and FICO Blaze Advisor. The past year or so has all been about using Drools Guvnor to enable business users (legal and operations teams) manage rules, and using the Drools rules engine to evaluate trade requests against those rules.

My preference in setting up web services is to use the Spring Framework to configure my application and manage its various components. However, I struggled to find much information online about how best to wire up a Spring web application to make use of Drools for rules evaluation. The Drools documentation does include a chapter on Spring integration, but I found that it didn’t seem to make the integration any simpler, and forced dependencies on older versions of Spring that I didn’t want to use. In the end, I decided to hand-crank the integration in my application, and it turned out to be quite easy to do.

So in the hope that it might be useful to someone else, I have knocked up an example project, which configures web services, which are backed by services that each make use of a Drools knowledge base to make decisions. That project can be found at GitHub:

https://github.com/gratiartis/sctrcd-fx-web

Feel free to grab a copy and play around with it. It’s built with Maven, and generates a Java web application, which makes use of Spring and Drools to provide a number of web services that could be part of a foreign exchange payments system. I won’t talk about it in depth now though, as it makes use of a variety of technologies. I will soon be posting more, talking about different specific aspects of that project.

Jan 172013
 

Working in the financial industry, I have become rather strict about avoiding doubles in Java. The trouble is that they are a floating point representation of a number, which is just an approximation of the real value. This can lead to some unusual results.

For instance, according to this, 0.34 + 0.01 is not equal to 0.35.

double x = 0.35;
double y = 0.34 + 0.01;
System.out.println(x + " : " + y + " : " + (x == y));

0.35 : 0.35000000000000003 : false

Those inaccuracies might seem very small, but it’s surprisingly easy for them to start impacting a real world application. Imagine you wanted to sell dollars and buy Iranian Rial. You would be getting almost 20,000 Rial for every dollar. At that rate, imprecise floating point values could easily impact the final amount being sent. Although with the current US trade sanctions against Iran, that could be the least of your problems.

If you are running reports on a history of transactions, then a large number of smaller transactions can add up to large enough values that the imprecise doubles start affecting your totals. Even if you’re not dealing in huge numbers, things can go wrong easily enough. If your process takes a number through a sequence of multiplications or divisions, errors can be magnified. If you have a business rule to always round up, then according to our calculation above, 0.34 + 0.01 = 0.36.

However, that’s enough about why doubles are bad for financial calculations. What caught me by surprise was running accumulate functions in Drools. I was writing code to react to currency exposures being at particular limits, which were all being added up from nice healthy BigDecimal values. However, the numbers I was getting from the ‘sum’ accumulate function were not equal to the numbers my unit tests were expecting. A little investigation showed that the sum accumulator was converting all my nice fixed precision BigDecimal numbers into doubles. Oh dear…

So after a little further investigation, I established that there are no BigDecimal accumulators for Drools, and a bug has been open since 2008. The only workaround mentioned was to write your own ‘sumBigDecimal’ accumulator function.

This didn’t seem like great progress, but I thought it seemed like a good opportunity to learn a new corner of Drools, so I knocked together this BigDecimalAccumulator implementation:

I am a bit puzzled that I’m not finding examples of this all over the place, as Drools has seen a lot of uptake in the financial industry, and it seems like an obvious thing that anybody using Drools for financial rules and calculations would need. Maybe there are loads of private repositories out there, each with their own implementations?

Anyway, in the absence of BigDecimal accumulator functionality in core Drools, feel free to grab this for your own applications.

Jan 162013
 

Have you ever struggled with the mass of .jar files that you can find in a directory of Java libraries? You have no idea what version each of them is and what its dependencies are. You want to put your own application jar in there, but you know that will mean needing to get hold of 20 other jar files to deal with its dependencies.

I certainly have trouble with this. I use the Drools Guvnor web application to manage business rules, but this sometimes requires that I place my own libraries in that web application’s lib directory. Some of these libraries are actually minimal Spring applications which need to do data access and invoke web services. This means that each of them does require multiple additional Jar files. It becomes difficult to keep track of what libraries I have added to that directory and what I need to add.

However I have come across a decent way of dealing with this problem. The shade plugin enables me to build a single .jar file containing all dependencies for an application. This way, I’m able to ensure that all the dependencies I tested against in my build are definitely the ones that have been deployed.

The following is a basic example of configuring the shade plugin in your pom.xml:

I also find it particularly handy for FitNesse where I’m able to run a quick script to download the latest version of an artifact from a repository, and I know that what I’m getting includes all the dependencies I need. If a dependency version changes, or is added, I don’t need to alter my deployment script.

 

Jan 152013
 

Sonatype Nexus is a repository for build artifacts, which is particularly handy if you have a Maven project. Once you have your Maven project configured, every time you run mvn deploy Maven will do a bit of building and then upload the resulting artifacts (.jar, .war, …) to the repository. If you browse Nexus you will then be able to find those artifacts with a unique name and download them.

This is all great, but if your project is running on a snapshot version, then every time you deploy to Nexus, the artifact file name will be appended with date and an ever-incrementing number. For my purposes, I wanted to be able to go on to a Linux test server where I have Apache Tomcat installed and grab the latest .war file. Maybe I need to relax more, but I was getting a bit irritated with having to manually find the snapshot in Nexus, copy the link and then fire off a curl -O -L http://... command every time I updated the project.

Fortunately it turns out that Nexus provides a REST API for searching. Unfortunately, it only returns the name of an artifact without the time-stamp. I think that this is intended to be a ‘good thing’ with Nexus automatically resolving the latest snapshot based on requesting the snapshot with no time-stamp. Unfortunately, requesting that artifact from the location indicated by the API results in a ‘not found’ response.

Therefore I knocked up a little Ruby script, which will go to the URI at which a full artifact list can be found, which includes resources such as poms, jars, sha1 and md5 hashes. It then parses the response XML to narrow down the results and selects the most recent artifact that matches the search criteria. Finally it will download the artifact.

The latest version of the script can be found as a gist on GitHub:
https://gist.github.com/1852106

Jan 152013
 

Originally posted @ gratiartis.org on May 12th 2011.

I have been playing around with Apache Camel for a couple of projects recently, and so far I’m very impressed. Camel is one of a number of frameworks that seem to have sprung up over the past few years in response to the book Enterprise Integration Patterns by Gregor Hohpe and Bobby Woolf. It attempts to provide mechanisms to support all the patterns described in the book. And it does so very well, from what I have experienced so far. So I thought I would mention a couple of things I have done with it.

A simple content-based router

The problem I was trying to solve was that a legacy application was designed to listen to a WebSphere MQ queue, which would contain requests for a variety of operations. A new application had been developed to handle a subset of these operations. I couldn’t have both applications listening to the same queue, so I needed to divert particular operation request messages to a separate new queue.

I needed to put together a simple content-based router that would inspect the header of each incoming message and route the message to a different destination depending on the operation name. I was able to implement this by defining a route which used XPath to select an endpoint based on XML attributes. This could be done in the Camel context XML file and the project contained no code outside this file.

A CSV to XML transform

Here, I was dealing with integrating two off the shelf applications, the aim being to facilitating exporting a document and meta data from one system and importing it into the other. When exporting a document from the first application, a CSV would be generated in a directory on the filesystem. The other application provided an import adapter, which required an XML trigger file. I needed a small application to follow the following steps:

  1. Listen for CSV files being dropped in a directory on the filesystem.
  2. Split the CSV up into separate requests for each document being exported.
  3. Generate an XML trigger file for each request.
  4. Drop the XML trigger file into a directory ready for import by the downstream system.

As well as providing middleware messaging adapters, Camel also supports defining endpoints that are directories on the filesystem, so it can automatically create a listener for a directory. To deal with the first two steps, I made use of opencsv to parse the CSV, but as I soon discovered, Camel also provided CSV unmarshallers.

I extended the Camel RouteBuilder and using the fluent DSL for Java, defined my routes and created a Splitter class that would take the unmarshalled CSV and output a list of messages to an internal queue., this looked a bit like the following. I then defined a route to pick the individual metadata messages off the internal queue and use a Processor to generate XML in the required format.

Further reading

Camel is very comprehensive and is also one of the best documented projects out there. I keep trying to implement something myself and then finding that there’s already something that will do the job for me.

These are probably the best starting points for info on any particular integration pattern:

http://camel.apache.org/enterprise-integration-patterns.html
http://camel.apache.org/architecture.html

And this was one of the better tutorial introductions to it:

http://architects.dzone.com/articles/apache-camel-integration

If Camel sounds good, you should also take a look at Spring Integration. It’s another framework based on the patterns in the Enterprise Integration Patterns book, but has that Spring tendency towards implementation through bean annotations. But you don’t have to pick one or the other; the Camel project has developed the camel-spring-integration library to provide a bridge from Camel components to Spring Integration endpoints:http://camel.apache.org/springintegration.html

Jan 152013
 

Originally posted @ gratiartis.org on April 5th 2008.

When at work, I’m generally in the worlds of Windows and Solaris. But these days I’m doing my home development work on a MacBook Pro. But I’m keen to make sure that I can do everything that I do at work so that I can experiment in my own time. So here’s a list of the software I use to develop on the Mac and where to get it.

Java Development

Eclipse (http://www.eclipse.org/)

Still my favourite IDE for Java development with a whole host of useful plug-ins.

NetBeans (http://www.netbeans.org/)

A decent IDE for Java development, but not up there with Eclipse yet. Version 6 is good though if you’re happy to pick up the development builds. Once that’s complete t will be a real challenger.

Maven (http://maven.apache.org/)

You want to make sure your builds work no matter what platform you’re on? This is a very good way of making sure that happens.

BEA WebLogic

I’m generally a Java EE developer, and the platform that I target at work is WebLogic. Take a look at my WebLogic on Mac OS X page for more information about how to get the server running on OS X.

TeX Development

I do quite a bit of writing using LaTeX for my typesetting. You’ll find a few examples on this site where I have used it to generate PDFs. In the past I have worked on Windows with TeXnicCenter which made working with a large project easy and I used the MikTeX distribution which contains the useful utilities that allowed me to script generating the work products. But what do I do now that I’m trying to do everything on the Mac? As you might expect with something as well established as LaTeX, there is plenty of software that can be used on all sorts of platforms.

MacTex (http://www.tug.org/mactex/)

MacTeX is a collection of front-ends, documentation and utilities for TeX development. I should warn you that it’s over 700MB, so it will take some time to download!

Jan 152013
 

Originally posted @ gratiartis.org on April 5th 2008.

I mentioned my use of the WebLogic Scripting Tool a little while back. I have noticed since then that a number of folks visiting this site are looking for example scripts. I have obviously written a number myself and I promise I’ll try to get around to posting them here. However until I get myself in gear, I thought I would point you at some useful examples that are already out there. I’ll expand this post as I find more…

 

First, make sure you sign up on http://dev2dev.bea.com/. That’s the BEA site supporting developers where you will find provides news, tutorials and samples to help you get going with WebLogic.

They have a number of projects and code samples that you will be able to get at. My recommendation for getting started is to go to the CodeShare section and have a look around at all the good stuff that has been provided by generous developers around the world.

There’s a WLST project maintained by the guys who developed it in the first place. This contains a whole load of scripts.

And to give you more of a head start, you can go to the Code Samples area of dev2dev and search for WLST, which will give you a list of samples worth looking at. Currently these include a Server Health Monitor (artifact S198), which will periodically check your runtime heap and execute queues and log the state to file.

Also, if you are looking at WLST for its server monitoring capabilities, you should know that BEA Guardian is now free!

Update

A few folks have asked about getting hold of some example scripts. Unfortunately most of what I have written is for work, so it is tied to work environments and not mine to share. However, I have created some simple scripts for sharing, that cover scripting the creation of a domain. These are available as GitHub gists for creating WebLogic domains: http://gist.github.com/589660

Jan 152013
 

Since I’m now playing around on a MacBook Pro I thought I’d see whether it was possible to get BEA WebLogic running on it. As it turns out it’s quite simple. These instructions seem to apply to anything from 9.0 upwards, but there’s a link to instructions for 8.1 below.

 

Here are some sites that I have drawn on for these instructions:

Originally posted @ gratiartis.org on Septenber 8th 2007.

Assuming that you’re familiar with WebLogic on other platforms you probaby already know you can get hold of it here:

http://commerce.bea.com/products/weblogicplatform/weblogic_prod_fam.jsp

Select the download page for the version you want. When selecting platform, choose the version for AIX. Others are designed for specific platforms, but this one is their ‘generic’ install that will work on pretty much anything with a JVM.

Start a console and navigate to where the downloaded JAR was saved and run:

java -Dos.name=unix -jar server100_generic.jar

Replace the JAR filename appropriately according to the version you got. The trick here is that it overrides the os.name environment variable so that the installer doesn’t make a mess of things.

And that’s it… the installer runs and WebLogic is installed.

This is as far as I have got, so I will update this as and when I come across any peculiarities.

Jan 152013
 

Originally posted @ gratiartis.org on April 16th, 2007.

The financial industry does seem to be loath to share the fruits of their efforts. There doesn’t seem to be a lot around. And certainly not much that is regularly updated. Maybe everyone is worried about sharing trade secrets, but the rules for calculations are well established and I’m guessing that everyone must be writing their own implementations or buying in over-priced modules.

I did manage to come across one called jFin, which presents itself as a “Java library providing financial date arithmetic; date adjustment, date offset, day count calculation and schedule generation.” In its first year, it has been oriented towards date calculations only, but there is now a 0.1 release of a trade module on the jFin SourceForge project. The project does look as though it’s producing some decent work, so I thought I’d post a comment here to remind myself to take a deeper look as soon as I get the chance.

jFin does seem a little bit odd though. It’s all developed by one person, so there doesn’t seem to be much of a community around it. However it’s also distributed under the GPL, but with no classpath exception, which seems very odd given what I would assume to be the target audience: financial institutions. It is unlikely that any financial institution would go along with releasing their own source code just because they wanted to use a library. Something like the classpath exception or distribution under the LGPL might make more sense, where a community could be encouraged to contibute to making the library more useful rather than forcing users to contribute source code for where they just use the library.

Jan 152013
 

Originally posted @ gratiartis.org on April 6 2007

As a developer of financial systems, I’m constantly disappointed by how difficult it is to perform precise decimal arithmetic in Java. It’s fairly common knowledge that the use of double is not much use for financial calculations. As a quick example, take a look at the following piece of code.

public static void main(String arg[]) {
    BigDecimal bd = new BigDecimal("58.99").add(new BigDecimal("0.99"));
    System.out.println("BigDecimal result: " + bd);

    double d = 58.99 + 0.99;
    System.out.println("Double result: " + d);
}

You would have thought both results should be the same. However, you end up with:

BigDecimal result: 59.98
Double result: 59.980000000000004

This is caused by the fact that in Java, operations on double primitive uses floating point arithmetic. The use of floating point arithmetic does make it relatively fast to perform the operations. The approximate nature of them may not matter in all situations, but for financial calculations it can cause all sorts of problems.

As shown above, this issue is resolved by using the BigDecimal. This makes use of precise decimal arithmetic. However, if you’re working on a relatively complex operation, the code bloat can be immense. I’m sure most folks would agree that

BigDecimal bd = new BigDecimal("58.99").add(new BigDecimal("0.99"));

is a lot harder to read than

double d = 58.99 + 0.99;

COBOL has maintained a lifespan beyond most poeple’s expections largely due to the fact that calculations use precise decimal arithmetic. This has meant that in banks and presumably elsewhere, there continue to be COBOL teams working on various systems. With the recent drive towards encouraging the use of domain-specific languages and the ease with which languages other than Java can be run on the JVM, I have been digging around to find out what people are using in these situations. Unfortunately, so far it looks as though back-end systems continute to use Java and C/C++ with additional (often third patry) precise math libraries. These allow precise math to be used, but as they are not integral to the language, they just cannot be as concise and readable as I would like.

This is where I should probably introduce Groovy. It’s billed as “An agile dynamic language for the Java platform”, with many of the features of other dynamic languages such as Ruby and Python. The syntax is deliberately similar to that of Java, as it is designed to be run on the JVM and interact easily with Java APIs. The reason I bring it up is that as a result of the philosophy of “no surprises” the Groovy Math model assumes exact decimal math as the default for calculations. Groovy literals with decimal points are instantiated as BigDecimal. Although it’s worth noting that if a calculation involves a double, the calculation will proceed using floating point math. You can read more about it at http://groovy.codehaus.org/Groovy+Math but my reason for interest is that for instance, 58.99 + 0.99 == 59.98 actually evaulates to ‘true’. This means that you can actually start working with exact math on the Java platform in a manner that is easy to read.

I’m not an expert on the internals of these things, so I would be keen to hear other people’s thoughts on the use of Groovy as a domain-specific language for financial calculations on the JVM. Are there better alternatives that I haven’t heard of yet?