Subscribe: UrBlog
Added By: Feedage Forager Feedage Grade B rated
Language: English
cache  client  code  data  database  domain  groovy  int  java  method  new  object  objects  public  return  server  string 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: UrBlog


John’s ramblings about software

Last Build Date: Sat, 26 Jan 2013 13:27:05 -0500

Copyright: Copyright 2013

Moved to Github Pages

Sat, 26 Jan 2013 13:27:05 -0500

My blog has moved to github pages. Please navigate here to check it out...

An Introduction to Node

Wed, 24 Aug 2011 14:07:06 -0400

Node is an evented I/O server built on Google’s V8 JavaScript engine. Node provides a simple way to build highly scalable server applications. This article will provide an introduction to Node along with installation details and a first server. more...

Scaling with Single Threading

Fri, 19 Aug 2011 20:36:22 -0400

The free lunch is over. To speed up applications we are told we must write multithreaded programs and avoid mutable state. Functional programming can help with it’s immutable state. There’s also Erlang with the Actor model or Clojure with it’s software transactional memory. One other option to consider is single threading your code. Following are a few examples where single threading was used to scale applications. more...

Implementing REST Authentication

Fri, 19 Aug 2011 20:34:15 -0400

While there is not much written about REST authentication, there does seem to be a common theme among the few articles written about it that REST services should be authenticated by signing the query parameters using a private key and making the calls over HTTPS. This posting will provide an example of the signing of query parameters using a simple Spring server. We’ll provide a small twist by putting the authentication information in headers. more...

Hosting a Maven internal repository on a file share

Thu, 17 Feb 2011 18:11:25 -0500

I spent some time today setting up an internal repository for my Maven build. I wanted to host just the artifacts that are used by my projects and not allow the project build to go outside of that repository. I first setup my repositories like this:

    <name>My Company's Internal Repositoryname>

The idea behind this setup is that I overrode the "central" repository and pointed it to my internal repository. This way Maven would not try to go out to if it did not find something.

And it did not work. After much research and trying many things, it turns out my URL needs to look like this:


Hope this helps someone in the future trying to setup a repository on a share.

Using a HostnameVerifier with Spring Web Services

Fri, 17 Dec 2010 18:11:51 -0500

I was working with a web service from a site that uses SSL with a certificate that was self-signed. When attempting to make the calls, I received the error: No name matching {web address} found The workaround for this issue is to provide a HostnameVerifer that skips the host name verification process. There is an example of how to do this here. I ran into this issue after I had a nice clean codebase using Spring's WebServiceTemplate and RestTemplate. It took some digging, but I was able to find the spots where I had to install the verifier. We start with a NullHostnameVerifier that returns true for everything: public class NullHostnameVerifier implements HostnameVerifier { public boolean verify(String hostname, SSLSession session) { return true; } } The extends which uses a The WebServiceMessage sender for HTTPS is which is found in the spring-ws-support-1.5.9.jar. We need to create one of these and set the HostnameVerifier into it and pass it along to the WebServicesTemplate: public void setWebServicesTempalate(WebServicesTemplate template) { HostnameVerifier verifier = new NullHostnameVerifier(); HttpsUrlConnectionMessageSender sender = new HttpsUrlConnectionMessageSender(); sender.setHostnameVerifier(verifier); template.setMessageSender(sender); this.template = template; } The org.springframework.web.client.RestTemplate is setup differently. It uses a org.springframework.http.client.ClientHttpRequestFactory to handle the connections. Stepping thru the code, I found the RestTemplate using org.springframework.http.client.SimpleClientHttpRequestFactory which has a protected prepareConnection(...) method I could override and catch the HttpsURLConnection which I could set the verifier in. First we need our own ClientHttpRequestFactory: public class MySimpleClientHttpRequestFactory extends SimpleClientHttpRequestFactory { private final HostnameVerifier verifier; public MySimpleClientHttpRequestFactory(HostnameVerifier verifier) { this.verifier = verifier; } @Override protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { if (connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setHostnameVerifier(verifier); } super.prepareConnection(connection, httpMethod); } } Now we can use that as the request factory in our RestTemplate: public void setRestTemplate(RestTemplate template) { HostnameVerifier verifier = new NullHostnameVerifier(); MySimpleClientHttpRequestFactory factory = new MySimpleClientHttpRequestFactory(verifier); template.setRequestFactory(factory); this.template = template; } Once the NullHostnameVerifer is in place in the WebServiceTemplate and the RestTemplate, we will no longer see the error [...]

Using Spring as a Factory Method

Thu, 11 Nov 2010 21:13:38 -0500

One common strategy in object-oriented program is to use the dependency inversion principle to decouple high level code from the low level details. To demonstrate this, let's use the movie example from Martin Fowler's Refactoring book. After some initial refactoring, we have a Movie class that can calculate it's charge based on days rented: // From book: 'Refactoring' by Martin Fowler public class Movie { public static final int CHILDRENS = 2; public static final int NEW_RELEASE = 1; public static final int REGULAR = 0; double charge(int daysRented) { double result = 0; switch (getPriceCode()) { case Movie.REGULAR: result += 2; if (daysRented > 2) result += (daysRented - 2) * 1.5; break; case Movie.NEW_RELEASE: result += daysRented * 3; break; case Movie.CHILDRENS: result += 1.5; if (daysRented > 3) result += (daysRented - 3) * 1.5; break; } return result; } }Next we replace the switch statement with polymorphism using the state pattern: // From book: 'Refactoring' by Martin Fowler public class Movie { public static final int CHILDRENS = 2; public static final int NEW_RELEASE = 1; public static final int REGULAR = 0; public static Price newPrice(int priceCode) { switch (priceCode) { case REGULAR: return new RegularPrice(); case NEW_RELEASE: return new NewReleasePrice(); case CHILDRENS: return new ChildrensPrice(); default: throw new IllegalArgumentException(); } } double charge(int daysRented) { return newPrice(getPriceCode()).charge(daysRented); } } public interface Price { double charge(int daysRented); } public class RegularPrice implements Price { public double charge(int daysRented) { double result = 2; if (daysRented > 2) result += (daysRented - 2) * 1.5; return result; } } public class NewReleasePrice implements Price { public double charge(int daysRented) { return daysRented * 3; } } public class ChildrensPrice implements Price { public double charge(int daysRented) { double result = 1.5; if (daysRented > 3) result += (daysRented - 3) * 1.5; return result; } }This requires us to create some sort of factory method to decide which Price to create based on the Movie type (such as newPrice in the example). Usually this occurs in a static method with a switch statement on type. In a large program where Price is used multiple times, this is an advantage because we only have to change the one switch statement. But what if we could get rid of that switch statement also? If you are using Spring, you can take advantage of the replace-method tag. You can pass it a class implementing MethodReplacer to replace a method in the class. That method could be an abstract factory method. Let's modify our Movie class so that newPrice is an abstract method: // From book: 'Refactoring' by Martin Fowler public abstract class Movie { public static final int CHILDRENS = 2; public static final int NEW_RELEASE = 1; public static final int REGULAR = 0; public abstract Price newPrice(int priceCode); double charge(int daysRented) { return newPrice(getPriceCode()).charge(daysRented); } }Now we create a handy method replacer utility class that joins a prefix with the first argument to create a bean name and looks up the bean in the context:public class BeanFactoryMethodReplacer implements MethodReplacer, ApplicationContextAware { private ApplicationContext context; private String prefix; public void setApplicationContext(ApplicationContext context) throws BeansException { this.context = context; } public void setPrefix(String prefix) { this.prefix = prefix; } public Object reimplement(Object obj, Method method, Object[] args) throws Throwable { String bean = ([...]

Custom Scheduling in Spring

Fri, 5 Nov 2010 22:43:00 -0400

Spring 3.0 has simplified task scheduling. As part if this, they have deprecated the MethodInvokingTimerTaskFactoryBean and ScheduledTimerTask. Instead you create a scheduler that implements the TaskScheduler interface and uses a Trigger to specify when a task is scheduled to run. The XML and annotations allow you to specify fixedDelay, fixedRate or cron string. These are fixed at run time. This works great for triggers that are fixed at run time, but does not allow you any way to modify these at run time. The TaskScheduler interface provides methods to schedule a task with a trigger, so this gives us an opportunity to pass in a custom trigger that can have it's trigger interval changed at run time. There are a number of ways to configure this. Here is a simple way I came up with that uses a single bean to schedule the task and change the fixedDelay at run time. This extends the example provided on the Spring blog noted earlier. First we need a class that takes the scheduler, task and starting delay. For simplicity, it will also implement the Timer interface. public class DynamicSchedule implements Trigger { private TaskScheduler scheduler; private Runnable task; private ScheduledFuture future; private int delay; public DynamicSchedule(TaskScheduler scheduler, Runnable task, int delay) { this.scheduler = scheduler; this.task = task; reset(delay); } public void reset(int delay) { if (future != null) { System.out.println("Cancelling task..."); future.cancel(true); } this.delay = delay; System.out.println("Starting task..."); future = scheduler.schedule(task, this); } @Override public Date nextExecutionTime(TriggerContext triggerContext) { Date lastTime = triggerContext.lastActualExecutionTime(); Date nextExecutionTime = (lastTime == null) ? new Date() : new Date(lastTime.getTime() + delay); System.out.println("DynamicSchedule -- delay: " + delay + ", lastActualExecutionTime: " + lastTime + "; nextExecutionTime: " + nextExecutionTime); return nextExecutionTime; } }Note the reset method which stops the scheduled task, changes the delay and then restarts the task. If you are changing the delay to a shorter delay, you want to restart with the new delay so it happens immediately. Alternately, you can skip canceling the task and the new delay is picked up on the next execution. The rest of the code is the same, except for the SchedulerProcessor which has the @Scheduled annotation removed from the process method:@Component public class ScheduledProcessor { private final AtomicInteger counter = new AtomicInteger(); @Autowired private Worker worker; public void process() { System.out.println("processing next 10 at " + new Date()); for (int i = 0; i < 10; i++) {; } } }In the XML configuration, we add a name to the scheduler and create the DynamicSchedule. We pass it the scheduler, the process method (wrapped in a MethodInvokingRunnable) and the default delay: Now we can add a separate process that changes the delay to a random delay t[...]

Working in Ubuntu and VMware Workstation

Fri, 9 Oct 2009 22:57:00 -0400

I'm trying to get myself up to speed on Linux, so I thought a good way to do that was install Ubuntu in VMware workstation and use it for my Java development work. VMware allows you to install tools so you can easily move the mouse between Linux and Windows, copy and paste, drag and drap and share folders. Should be easy enough, right?

Here was my experience:

  1. I installed Ubuntu 9.0.4 Desktop i386 into WMware Workstation 6.5.2. VMware reconized the OS and took me thru an expidited installation. Ok so far.
  2. Installed vmware tools into the Ubuntu VM. The installation was succesfull, but mouse features and sharing would not work.
  3. After much investigation via Google, I found this which described how to change code in the vmhgfs module. Additionally, in the comments, someone pointed out I needed to do the following: sudo apt-get remove xserver-xorg-input-vmmouse followed by: sudo apt-get install xserver-xorg-input-vmmouse. After a few attempts, I got it working.
  4. Time to install Java 1.6 JDK. I downloaded the JDK and installed using the .bin in the /opt directory (which is the correct place to install add on software per this article. I then set my JAVA_HOME in my .bashrc file and it to /etc/profile.d per this article. Reboot and java -version returns the correct value.

So after many hours of effort, I have a usable Ubuntu VM. Next to try to install MyEclipse:

  1. Download MyEclipse 7.5 Linux all in one
  2. Run the installer as root into /opt/Genuitec
  3. sudo chmod -R 777 Genuitec

I run MyEclipse and it's usable, but I cannot run the new Pulse Add/Remove software feature and I'm unable to get Pulse to work correctly, so I cannot add any plugins. I've tried installing using my login id and still no luck. I also tried a clean Eclipse install and using the MyEclipse update site and that would not go either. I decided to punt on using MyEclipse in Linux and instead loaded the standard Eclipse 3.5 with Eclipse DB and Web plugins.

For the last step, I shared my workspaces folder from Windows with the VM. I then setup a new workspace under my Linux home directory, linked to the projects on my Windows folder and imported them into the workspace. I can now work on the same Eclipse projects from both Windows and Linux!

GSQL and GString

Fri, 21 Aug 2009 23:10:00 -0400

My Groovy learning continues. In a previous post, I complained about my issues with Groovy Sql doing strange things with GStrings with substitutions. Today, while waiting for my machine to recover from an operation (new laptop came in today, horray!), I was reading up on Groovy and found this little paragraph in the GString page:

GString Use Cases - GSQL

Another use case for GString is GSQL where parameters can be passed into SQL statements using this same mechanism which makes for a neat way to integrate Groovy with other languages like SQL. GroovySql then converts the expressions to ? and uses a JDBC PreparedStatement and passes the values in, preserving their types.

While that is certainly a "neat" thing, it sure is confusing to a new user of the language.

Groovy Gotchas

Fri, 14 Aug 2009 18:52:00 -0400

Every now and then I give groovy a try (see last time). My latest return to groovy is at work where we are using easyB to build automated tests. A developer on my team created a script to take the easyB tests and spit out standard test case spread sheets from those tests with the results to make the ISO people happy. It works pretty slick.

Anyway, I'm now doing some groovy coding to implement some of those tests. Here is the first gotcha I've run into.

I'm loading data into the database using groovy.sql.SQl. I wanted to put the database schema in a variable so I could change it later. I started using gstrings for SQL because it's quick and easy and I'm only writing test scripts. Here's an example:
def schema = "MYSCHEMA"
def name = "John Doe"
def db = Sql.newInstance("")
db.execute("insert into ${MYSCHEMA}.MYTABLE (NAME) values (${myName})")

It turns out that does not work. If I hard code the schema name, it does work. Since I don't want to do that, I tried using prepared statements:

def schema = "MYSCHEMA"
def name = "John Doe"
def db = Sql.newInstance("")
db.execute("insert into ${MYSCHEMA}.MYTABLE (NAME) values (?})", [name])

That works. I expect this is the first of many gotchas I'll run into in the coming weeks of groovy coding.

Transmitting Unicode data between C++ and Java

Wed, 12 Nov 2008 13:56:55 -0500

We ran into an issue this week were we had to figure out how to transmit Unicode data between a C++ program and a Java program using TCP. We have a working program that is sending ASCII just fine. We expected the C++ Unicode work would be difficult and the Java work would be easy. It turns out the C++ side was not as difficult as we thought. The Java side turned out to be easy, but it took some time to figure out how to make it work. Here's a quick explanation of what we found: C++ Most of our C++ code is using the standard library (i.e. std::string) and boost::asio for the networking. After a bit if research, I created a tstring.hpp file using code I found here and here. I changed the networking code to use the new std::tstring instead of std::string and was able to deal with Unicode data. Here's an example of the asio code to read data sent from Java. Java sends a header with "file0000000000" where the 10 digits contain the data length, followed by the data itself. Notice the buffer size is the size * sizeof(TCHAR) to account for the fact that wide char are twice the size of normal char.class session : public boost::enable_shared_from_this { public: void read_header() { buffer_.resize(14); boost::asio::async_read( socket_, boost::asio::buffer(buffer_, buffer_.size() * sizeof(TCHAR)), boost::bind( &session::handle_read_header, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void handle_read_header(const boost::system::error_code& error, size_t bytes_transferred) { if (error) return; std::tstring data(buffer_.begin(), buffer_.end()); short length = boost::lexical_cast(data.substr(4)); buffer_.resize(length); boost::asio::async_read( socket_, boost::asio::buffer(buffer_, buffer_.size() * sizeof(TCHAR)), boost::bind( &session::handle_read_data, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void handle_read_data(const boost::system::error_code& error, size_t bytes_transferred) { if (error && error.value() != 2) return; std::tstring data(buffer_.begin(), buffer_.end()); // process data read_header(); } private: tcp::socket socket_; std::vector buffer_; int count_; }; Java For an example, we created a simple Java program that would load in a Unicode file, append a header and send it to the C++ code above. What took a great deal of time was figuring out how to get the data in the correct format. It turns out the way the C++ program was looking for data was in UTF-16LE format. We took our data string and called getBytes("UTF-16LE") to get the data in the correct format to send.String data = getFileContents(); Formatter f = new Formatter(); String header = f.format("file%010d", data.length() * 2).toString(); data = header + data; byte[] buffer = data.getBytes("UTF-16LE"); Socket socket = new Socket(address, port); BufferedOutputStream bis = new BufferedOutputStream(socket.getOutputStream()); try { bis.write(buffer); bis.flush(); } finally { bis.close(); } In the end, this turns out to be easy to do. It just takes a bit of time to figure out the settings. We had to spend time searching for bits and pieces of info to put this together. If you happen to know any good resources to help others with this, feel free to add a comment.[...]

Chippewa Valley Code Camp Slides

Wed, 12 Nov 2008 13:06:38 -0500

The slides from the Chippewa Valley Code camp are available. There were some technical glitches with my Boost presentation so we were only able to view the slides. Fortunately, I had lots of code on them so it turned out well. Hats of to Doug Rhoten and Dan Krueger for organizing the code camp.

Chippewa Valley Code Camp

Sun, 26 Oct 2008 22:13:20 -0400

The Chippewa Valley .Net User Group is holding its first code camp on November 8. There will be two tracks; a Microsoft Technology Track and an Agnostic/Cross-over Track. I'll be giving a presentation on using the Boost libraries in C++. In addition to .Net topics, there will be Java, Rails, C++ and other topics. If you are a software professional in the Western Wisconsin area, this will be a good chance to meet your peers and maybe learn a thing or two.

What: Chippewa Valley Code Camp
When: Sat, Nov. 8, 2008, 8AM – 5:30PM
Where: Chippewa Valley Technical College, 620 West Clairemont Ave., Eau Claire, WI
Cost: Free

How to Determine MaxHeap for JNI

Mon, 22 Oct 2007 18:03:19 -0400

We have a Windows application that starts up the Java VM in a DLL. One of the parameters we can pass to the DLL is the Xmx setting to use when starting up the JVM. When we sent our application out to clients, we quickly found out that not all machines could handle the Xmx setting we wanted, so we had to figure out a way to determine the maximum setting we could have on a machine and lower the Xmx setting to match that if it was to high.

It turns out it was not quite as easy as calling GlobalMemoryStatus() to see how much memory was available. The answer was to determine how much memory the JVM would take and use VirtualAlloc to try to reserve that much memory. If I couldn't, I would lower the Xmx and try again until I found a workable Xmx setting.

When the JVM allocates memory, it takes the Xmx (MaxHeapSpace) setting and adds in the -XX:MaxPermSize setting. Here's an example function that takes the Xmx and -XX:MaxPermSize settings and determines a workable Xmx from it:

bool CanAllocate(DWORD bytes)
LPVOID lpvBase;

lpvBase = VirtualAlloc(NULL, bytes, MEM_RESERVE, PAGE_READWRITE);
if (lpvBase == NULL) return false;

VirtualFree(lpvBase, 0, MEM_RELEASE);

return true;

int ProcessMaxHeapSize(DWORD maxHeapSize, DWORD maxPermSize)
int numberOfPages = 0;
DWORD memoryNeeded = 0;


// make it fit in the page structure
maxHeapSize = maxHeapSize + (maxHeapSize % sSysInfo.dwPageSize);
numberOfPages = maxHeapSize / sSysInfo.dwPageSize;

memoryNeeded = maxHeapSize + maxPermSize;
while (!CanAllocate(memoryNeeded) && numberOfPages > 0)
numberOfPages --;
maxHeapSize = numberOfPages * sSysInfo.dwPageSize;
memoryNeeded = maxHeapSize + maxPermSize;

return maxHeapSize;

Another interesting issue we have is the fact that the JVM cannot allocate as much memory when started in our DLL as it can when started at the command line. Tony Printezis was kind enough to point out the reason for this in the Java Developer Forum thread I opened concerning this issue:

The JVM requires a contiguous address range for the entire heap (there are many reasons for this, I can go over them if you really want me to). If a DLL decides to pin itself in the middle of the address space, then we cannot allocate the heap contiguously and we have to use the largest of the two "halves".

Debugging a hung thread in Eclipse

Fri, 8 Sep 2006 16:12:38 -0400

I had a Swing application that was hanging in the Swing event thread and could not figure out why. I put some System.out.println() statements in areas I thought were causing the problem but nothing came up. Then I noticed that when I was running the app in debug mode in Eclipse, I could highlight the AWT-EventQueue-0 thread in the debug view and press the suspend button. This suspended the thread and brought me right to the line of code where it was hung on. It was hung in a synchronized block in JComponent. I never would have thought of looking there. That little Eclipse feature saved me a great deal of time.


Is Swing not aimed at business developers?

Thu, 17 Aug 2006 18:33:41 -0400

I got what seemed to be a fairly reasonable request from our UI designer. When a field has a validation error, the focus should stay in that field and no other actions should occur until it is corrected or the user closes the screen. I did a little research and it looked like the InputVerifier was the correct tool to use. Little did I know the input verifier does not work correctly (See Bug 4533820). With some help from the comments on that bug as well as help from Kleopatra via the Wayback Machine, I was able to get something working in a few days of work. Fortunately, we have our own look and feel, so I was able to implement the fixes there.

Edit masks are another tool used in a business application. Turns out the JFormattedTextField is nearly worthless as is. MaskFormatters are very dumb objects. A formatted text field for number allows you to enter characters, it just won't let you leave the field until it's fixed (with no error of course). There went another few days of work creating custom formatters to handle the different data types we need.

To give Swing credit, I was able to get in there, see the code and make the fixes. But imagine a mid level business programmer trying to write a program in Swing. They would conclude that Swing was to complex as they spend many days trying to figure out how to do things that were simple to implement in PowerBuilder or Visual Basic 6.

Building a domain object framework - Caching

Mon, 29 May 2006 23:45:06 -0400

I'm going to skip over Aggregates, Services and Factories. Those have been well covered in many books. This installment will cover caching. When we talked about Entities, we noted they are differentiated by a thread if identity. The Entity object base class was setup as Identifiable and uses a serializable id field. Take the following model: Lets imaging an invoicing screen with a combo box for selecting products. We first load a list of products for the combo box. Then we load the invoice by joining the invoice, invoice line and product tables. We will end up with duplicate objects in memory for some of the products; the products associated with invoice lines are also in the combo box list. If your invoicing system allows the same product on the same invoice, you could have many instances of the same product. If you business logic updates the product data on this screen, you have a problem. What we want is a unique instance of each Identifiable object in memory. The way we solve this is with a cache. When you read in the list of Products, keep a reference in the cache by class and id. When you load the products on the invoice, first check in the cache for a product with an id. If it's already in the cache, use the object in the cache instead of creating a new instance. If you are using an O/R mapper, you get this already for a two tier application. For example, Hibernate has a Session object that handles this. Where things get tricky is in a 3-tier rich client system. Lets look at our example in that setting. We issue a call to the server to get the product list. The server loads the Products and sends them over the wire. We later issue a call to the server to get an invoice. We pass the invoice, with associated products, over the wire. When the invoice is deserialized on the client machine, it will automatically create new instances of products and we are back with the same problem. The O/R mapping cache did not help us, so we need our own cache in our framework. I use the term Registry for my cache of objects. I got that term from Martin Fowler books and it seems to fit well. The registry will keep a cache of Identifiable objects by class and id. Java serialization has a method called readResolve(). This method allows us to return a different object when deserialization is complete. We will add one of these methods to our Entity object. If our object is in the registry, we will return the one in the registry instead. We also need to determine which registry to use. We will use a thread local variable. Before calling a method that loads domain objects on the server, we will require the code to set the current registry. Here is the base class for the Registry: public abstract class Registry { protected static ThreadLocal reg = new ThreadLocal(); public static Registry getThreadRegistry() { return (Registry) reg.get(); } public static void setThreadRegistry(Registry registry) { reg.set(registry); } public abstract Identifiable put(Identifiable obj); public abstract boolean contains(Identifiable obj); public abstract Identifiable get(Identifiable obj); public abstract Identifiable get(Class identifiableClass, Serializable id); public abstract Collection getAll(Class clazz); public abstract Object resolve(Identifiable obj); public abstract void flush(); } Here is the new method in our Entity object: protected Object readResolve() throws ObjectStreamException { Registry registry = Registry.getThreadRegistry(); if (registry == null) return[...]

Building a domain object framework - Value Objects

Mon, 15 May 2006 22:54:55 -0400

From p.99 of Domain Driven Design:

When you care only about the attributes of an element of the model, classify it as a VALUE OBJECT. Make it express the meaning of the attributes it conveys and give it related functionality. Treat the VALUE OBJECT as immutable. Don't give it any identity and avoid the design complexities necessary to maintain ENTITIES.

There's no way to enforce that value objects are immutable in Java, so we will need to do it by convention. The attributes of the value object will differentiate it from other value objects, so we will create a base ValueObject that implements equals and hashCode based on the attributes. The interface will extend Serializable so our Entities can use them. We will also make them Comparable so they can be sorted.

public abstract class ValueObject implements Serializable, Comparable {

   public int hashCode() {
      return HashCodeBuilder.reflectionHashCode(this);

   public boolean equals(Object obj) {
      return EqualsBuilder.reflectionEquals(this, obj);
   public int compareTo(Object obj) {
      return CompareToBuilder.reflectionCompare(this, obj);


A single name field is not adequate for our example Customer. We will make a Name value object with first, middle and last name.

public class Name extends ValueObject {

   private static final long serialVersionUID = 1L;

   private String firstName;
   private String middleName;
   private String lastName;
   public Name(String firstName, String middleName, String lastName) {
      this.firstName = firstName;
      this.middleName = middleName;
      this.lastName = lastName;
   public String getFirstName() {
      return firstName;

   public String getMiddleName() {
      return middleName;

   public String getLastName() {
      return lastName;


Now we change Customer to use the Name value object:

public class Customer extends EntityObject {

   private static final long serialVersionUID = 1L;

   private String accountNumber;
   private Name name;
   public Customer() {

   public String getAccountNumber() {
      return accountNumber;

   public void setAccountNumber(String accountNumber) {
      this.accountNumber = accountNumber;

   public Name getName() {
      return name;

   public void setName(Name name) { = name;

Next up: Aggregates

Building a domain object framework - step 1

Fri, 12 May 2006 08:09:21 -0400

I'm starting a series on building a framework using concepts in Domain Driven Design by Eric Evans.

Our requirements are to support a n-tier rich client application using a relational database for persistence. We would also like the flexibility to run as a fat client application if need be and also have the ability to attach a web front end to the application at a later date.

We will start with a layered architecture. This framework will be partitioned into 4 layers: UI, Application, Domain and Infrastructure.

The center of a domain object framework are domain objects in the domain layer. The first type of domain object I'll cover is an Entity object. Eric Evans describes an entity object on page 91 as follows:

Some objects are not defined primarily by their attributes. They represent a thread of identity that runs through time and often across distinct representations. Sometimes such an object must be matched with another object even though attributes differ. An object must be distinguished from other objects even though they might have the same attributes. Mistaken identity can lead to data corruption.

An entity object represents a thread of identity, so it must be identifiable.

 * A class is identifiable if it has an id property
public interface Identifiable {
   Serializable getId();

Since it runs thru time and across distinct representations, we'll tag it with the Serializable interface. That gives us a starting point for an EntityObject.

 * An entity object has an identity.  We will use that object to
 * differentiate between other objects by overriding hashCode and
 * equals to be based on the id if it is available.
 * An entity object can live beyond the running program so they
 * are serializable.
public class EntityObject implements Serializable, Identifiable {

   private static final long serialVersionUID = 1L;
   private Serializable id;
   public EntityObject() {

   public Serializable getId() {
      return id;
   public int hashCode() {
      if (id == null) return super.hashCode();
      return id.hashCode();
   public boolean equals(Object obj) {
      if (id == null) return super.equals(obj);
      if (obj == null) return false;
      if (!(getClass().isAssignableFrom(obj.getClass()))) return false;
      return id.equals(((EntityObject) obj).getId());


The id field is used to implement equals() and hashCode() if it exists. Otherwise, we use the super implementation for these. Usually an entity object is stored in a database table, so the id field is populated from the primary key. How that happens will be described when I discuss the data access layer.

Here's an example entity object:

public class Customer extends EntityObject {

   private static final long serialVersionUID = 1L;

   private String accountNumber;
   private String name;
   public Customer() {

   public String getAccountNumber() {
      return accountNumber;

   public void setAccountNumber(String accountNumber) {
      this.accountNumber = accountNumber;

   public String getName() {
      return name;

   public void setName(String name) { = name;

Next step is value objects...

Edited to remove setter from Identifiable interface.

When 1 != 1

Wed, 10 May 2006 13:41:12 -0400

Am I talking about new math? No, just Java's numeric handling. This code returns false:
Number a = new Long(1);
Number b = new Integer(1);
System.out.println(a.equals(b)) // false

Many of you knew this as did I. It's still a pain and easy to forget. I also get burned with floating point impression. I'm writing code to round money up and the round to value must divide evenly into 1. So it should be as easy as this:

double roundTo = 0.01;
if ((100 % roundTo) == 0) ...

Except 100 % 0.01 uses floating point arithmetic and so returns 0.009999999999997919. So, I use BigDecimal (since I already have it in my Money class) and force it to use integer arithmetic giving the following lovely piece of code:

BigDecimal value = BigDecimal.ONE;
BigDecimal divisor = BigDecimal.valueOf(roundTo);

int scale = Math.max(value.scale(), divisor.scale());
BigDecimal mult = BigDecimal.valueOf(10.0).pow(scale);
BigDecimal valueScaled = value.multiply(mult);
BigDecimal divsorScaled = divisor.multiply(mult);
if (valueScaled.remainder(divsorScaled).doubleValue() == 0) ...

I'm sure there's some math trick I'm missing to make this easier, but I'm not a math major and don't have time to figure it out.

That wasn't exciting enough? Throw in Sybase JDBC which sometimes returns Double and sometimes returns BigDecimal for double fields in the database. Fortunately my mapper class has the ability to customize how data is loaded in an object, so I figure I can do this:

public Object toPropertyValue(Object columnValue) {
   if (columnValue == null) return 0;
   if (columnValue instanceof BigDecimal) {
      return ((BigDecimal) columnValue).doubleValue();
   return columnValue;

Think that will work? NOT. That return 0 returns an Integer 0, not a Double 0. Since the mapper code uses reflection to put the value in the Double field in the class, it throws an exception. The code must be this:

public Object toPropertyValue(Object columnValue) {
   if (columnValue == null) return new Double(0);
   if (columnValue instanceof BigDecimal) {
      return ((BigDecimal) columnValue).doubleValue();
   return columnValue;

One would think this would be easier in a programming language that's used so frequently in business. I personally blame this on using primitives for numbers instead of real objects. If you look at Smalltalk, the numeric objects don't have this issue.

I'll save my thoughts on Java Dates for a later date...

Who's doing domain driven development?

Mon, 8 May 2006 21:59:14 -0400

For quite a few years, I've been a strong OO proponent. I spent a lot of time studying books on OO design. When we started working with Java a few years ago, I was able to implement the first prototype of a 3-tier Swing application and I put my learning into practice. The design of the system is similar to the concepts in Domain Driven Design. It was split into the four layers of UI, application, domain and data access. It used domain objects as the central place for business logic. In the past year, our company formed an architecture team and we found a framework in the growing Java codebase.

As we've been interviewing Java developers, I ask them questions about domain objects and most have not heard of this concept before. Many of these have been senior level developers with many years of Java experience. Many understand how to use OO to deal with technical details in frameworks, but the best I see for domain logic is using Hibernate to create glorified data transfer objects. While this is quite a bit better than sprinkling SQL in your business logic, you still end up writing your business logic in a procedural fashion.

I'm curious how many of you out there are building your applications with a rich domain layer? I'm also thinking I will start a little series on this blog on the steps to build a framework for supporting developing a n-tier rich client application with a rich domain layer. Maybe if it's useful I can turn it into a presentation for next year's JavaOne or OPSLA.

OR Mapping vs. Active Record

Sat, 22 Apr 2006 21:26:59 -0400

I'm working thru the Ruby on Rails book and I'm finding Active Record interesting. I've always preferred a rich domain model, but the price for that has been mapping to a relational database. Even when using a tool like Hibernate, there is still the work of setting up the mapping and the conceptual overhead of understanding that we are loading a graph of objects in memory instead of a row set from the database. I'm finding many developers have difficulties with that and end up using the domain objects as fancy data transfer objects; that is the objects just have getters and setters and no business logic. Active Record in Rails removes all of the mapping work (assuming you use their naming conventions) and feels closer to the data model. This approach seems to be a better fit for projects that are CRUD oriented than the OR mapping approach. I still wouldn't use it for a large complex project like I'm working on now, but I'll certainly give it serious consideration in the future on smaller projects.

How Your Toolset Affects the Way You Program

Fri, 16 Jul 2004 08:34:20 -0400

So I found Agile Planet the other day and came upon a Darrell Norton post which agreed with a Steve Maine post in which the author proposes that an object oriented business layer doesn't buy you much. Interestingly, they are both .Net developers. I think this is the key to understanding why they think this way. The .Net framework is built around creating data sets from SQL or XML and connecting those data sets to screen elements. Data sets are also easy to use in distributed environments; they know how to marshall and unmarshall themselves. Plus, they handle all the data access for you. But what do you have if you want to build business objects? Not much other than some binding capabilities on GUI elements. You have to build the persistence and distribution code from scratch. So if you have to get a project done quickly in .Net, which way would you go? I've worked in PowerBuilder for many years, and there is a similar effect there. PowerBuilder is a fully object oriented 4GL development tool. The 4GL part comes from the DataWindow. The DataWindow allows you to enter a SQL statement and layout the fields from the SQL's result set in many different forms. It then automatically retrieves the data, keeps track of changes and applies the changes to the database. It also triggers events when data changes so you can write code in PowerScript to validate the data. Of course you have now committed the cardinal sin of mixing your GUI, business logic and data access code all together. While PowerBuilder supports all the necessary elements of OO, guess what's available to help you build domain objects...nothing. You have to build the persistence, distribution and GUI binding code from scratch. Guess how many OO domain layers can be found in PowerBuilder land... Are things any better in Java? Yes and no. Since there hasn't been a standard RowSet, most developers have had to figure out persistence themselves. This has led to a number of O/R mapping libraries. There's still no distribution help (most people punt and use DTOs) and no GUI binding, so a lot of work is still required to do real domain logic in Java (as I have personally found out). Even with the nice O/R mapping libraries available, I'm willing to bet most Java development is done with some custom object that just wraps a SQL result set instead of going thru the trouble of building a domain model. So are there any tools that make it easy to build business objects? How about Smalltalk? Nearly every Smalltalk comes with a real MVC implementation that allows you to bind object properties to controls. Distribution of objects is built into many Smalltalks. You can use the Gemstone database on the backend and all the persistence is taken care of for you. And all this was available a decade ago. So what's the lesson? Tools have certain ways they want you to use them. Tools like PowerBuilder and .Net want you to pass around SQL result sets. Tools like Java make you write everything from scratch. Tools like Smalltalk want you to make objects. So folks using .Net are going to avoid fighting the tool and assume OO is not a good thing for the business layer. Folks using Java are going to write lots and lots of libraries. And Smalltalk folks will shake their heads and wonder when people will finally get a clue. [...]

The simplest thing != (EJB && O/R Mapping)?

Wed, 12 May 2004 23:19:45 -0400

One of the first things I've always done when starting a new Java project was to obtain an O/R mapping library. Originally, it was VBSF and lately it was Hibernate. In the back of my mind, my XP voice would always ask why I'm involving large, complicated libraries before I'm sure I needed them.

Well, it turned out that Hibernate couldn't handle some of the strange things in our database and it took way to long to initialize. We ripped it out and we now have a much simpler persistence layer. It consists of a handful of utility classes that generate SQL and load results into objects. The only hard part is dealing with collection associations and lazy loading, but that was hard in Hibernate too. Oh, and the domain layer is no longer cluttered with additional classes needed to make Hibernate happy.

Then there's EJBs. We were building a distributed Java application and I assumed that meant I needed SessionBeans for each component in my system. But my application also needed to run as a fat client app in some situations, so soon I had all kinds of interfaces and glue classes to implement a component. It was a pain to add or change methods. Then I switched to the command pattern and removed all the interfaces and glue classes, as well as dependence on EJB. I still use a SessionBean to process commands in a 3-tier setup, but my application code is unaware of it.

Interestingly, I picked up the command idea from Gavin King (ref).

So next project I start, I'm going to be a little more cautious about jumping on the latest Java craze and only add frameworks when absolutely necessary.

Not So Groovy

Fri, 7 May 2004 14:32:35 -0400

When Groovy first came out I was quite excited about the prospect of a scripting language for the JVM that had closures. I first tried it out a few months ago and was disappointed with the shell, so I put it aside for a while. This week I was trying some Java2D examples in Jython and was curious how Groovy would compare. I downloaded 1.0 beta4 and tried my Jython example in Groovy. For this example, I'll only display some text to the screen using the Graphics object. Here's the Jython code: from javax.swing import * from java.awt import * from java.lang import * class TestPanel(JComponent): def __init__(self): self.setBackground( self.text = "Testing" def paintComponent(self, g): r = self.getBounds() g.setColor( g.fillRect(0, 0, r.width, r.height) g.setColor(Color.white) g.drawString(self.text, 50, 50) if __name__ == "__main__": panel = TestPanel() frame = JFrame("Jython Test Panel", size=(260,200)) frame.contentPane.add(panel) frame.windowClosing = lambda e: System.exit(0) panel.repaint() So I made the following naive translation to Groovy: import java.awt.* import javax.swing.* class TestPanel extends JComponent { TestPanel() { setBackground( this.text = "Testing" } paintComponent(g) { r = this.getBounds() g.setColor( g.fillRect(0, 0, r.width, r.height) g.setColor(Color.white) g.drawString(this.text, 50, 50) } static main(args) { cv = new TestPanel() fr = new JFrame(title:"Groovy Test Panel", size:[260, 200]) fr.windowClosing = { e | System.exit(0) } fr.getContentPane().add(cv) cv.repaint() } } I run the script and am told WARNING: Cannot find class: JComponent due to: java.lang.ClassNotFoundException: JComponent". Turns out there's a bug in Groovy with importing swing stuff, so I change the imports... import java.awt.* import javax.swing.* import javax.swing.JComponent import javax.swing.JFrame ...and try again. Now I am greeted with: Exception in thread "main" groovy.lang.MissingPropertyException: No such property: text for class: TestPanel. Reason: groovy.lang.MissingMethodException: No such method: setText for class: TestPanel with arguments: [Testing]. Turns out I need to declare the text instance variable... class TestPanel extends JComponent { text TestPanel() { setBackground( this.text = "Testing" } Now it runs, but the window comes up blank. Arrgg. Well maybe Groovy needs a little more type info, so I add Graphics to the paintComponent method call. The window is still blank. Maybe I need to add void to the paintComponent call. Still nothing. How about now adding public to the paintComponent call. Still nothing. How about adding an explicit import for java.awt.Graphics. Now I know it's getting called because I get the following error groovy.lang.MissingMethodException: No such method: fillRect for class: sun.java2d.SunGraphics2D with arguments: [0, 0, 252.0, 173.0]. After some head scratching, I tried casting the values I pass to fillRect: g.fillRect(0, 0, (Integer) width, (Integer) height)And now I get groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method: drawString. Cannot resolve which method to invoke due to overlapping prototypes between: [class java.lang.String, [...]

How could I get by without CGLIB?

Thu, 6 May 2004 13:32:13 -0400

CGLIB has saved me a great deal of development time. Here are a few examples:

Persistent Collections When we load a domain object that has a related collection of items (say an Invoice and it's InvoiceLines), I need a way to keep track of lines added and removed from the collection. The way to do this is to create custom collection classes that wrap the built in collection and keep track of objects passed into add() and remove(). Instead of having to write all these custom classes for each type of collection, I just used CGLIB with a single MethodInterceptor for all collections.

Lazy Loading We don't always want to load the full object graph from the database when retrieving domain objects from the database. Say I load a list of Invoices that match some criteria. I don't need to get the associated Customer for every object; only a few select Invoices might have their Customer's accessed. I used CGLIB with a MethodInterceptor to a create a proxy for the domain object. The intercepter calls a LazyLoad method when you first access a method on the domain object to load the actual object. If there's no LazyLoad method available, it throws a NotLoadedException.

Cache Entries As I've mentioned earlier, our client cache ensures unique instances of objects based on an object's id. Now let's say I load an Invoice with a LazyLoaded for Customer with id of 100. On another server call, I actually get Customer with id 100. So the Customer exists in my cache, but the Invoice would still get NotLoadedException even though Customer 100 is in the cache. CGLIB to the rescue again. When domain objects are loaded into my cache, I use the readResolve method in the domain object to resolve them with the cache. If the object is already in the cache, I return the cached object. If a LazyLoad proxy is in the cache for that item, I replace the LazyLoad proxy in the cache's proxy with the real object. Any other domain object referencing that LazyLoader now has the real object instead.

The only downside to this approach is in debugging. Using Enhancer.enhance() creates a subclass of the class I'm enhancing leaving all the instance variables showing in the debugger. Developers have to know to look for the real object wrapped inside instead to see the actual contents. We also get errors from Eclipse debuggers when we set a breakpoint in a domain object because there's no source code available for the enhanced subclass created by CGLIB. If anyone knows a workaround (other than only using Interfaces for all domain classes), I'd love to here it!

Side Note If only I could be working in a dynamic language such as Smalltalk or Python. The proxy class would be as simple as this:

   class Proxy:
      def __init__(self, obj):
         self.obj = obj
      def __getattr__(self, name):
         return getattr(self.obj, name)
      def __setattr__(self, name, value):
         setattr(self.obj, name, value)		

Distributed Domain Objects

Mon, 3 May 2004 14:12:30 -0400

We're working on a domain driven distributed Java program with a Swing GUI. It has rich domain logic and much of that must run on the client. This means using Data Transfer Objects (DTOs) is not acceptable for us. Since little has been written about this (beyond a few hints from Rickard), I thought I write a few thoughts about it while I'm in the process of writing some of this plumbing. Identity Each domain object must have a unique identity independent of it's JVM identity. Since most of our domain objects are persisted in the database, that identity is the record's primary key. Our base DomainObject class contains a Serializable id. This is set to the primary key from the database. In cases where the primary key is a composite id, we create a id class that contains the composite elements. The equals and hashCode methods are then overridden on the base DomainObject class to use the id. Persistence If your lucky enough to use an O/R mapper such as Hibernate, all the persistence issues are handled for you. In our case we can't, so we had to build our own cache to make sure there is only one instance of each unique DomainObject in memory in a JVM. We also had to build our own "PersistentCollection" class to track changes to collections and a proxy class for handling lazy loading of objects. Serialization When a domain object is passed from server to client, it gets recreated on the client outside our database cache that's running on the server. If I load a "User" in one server access, then later load a "Group" that contains that "User", I'll have two instances of the same "User" on my client. This is bad. The solution is to create a client side cache of domain objects. Our DomainObject class than has it's readResolve overridden to see if it's already in this client side cache and return the cached version instead. Commands To make matters worse, our code needs the ability to run as two-tier/fat-client application. Following the suggestion of someone on the Hibernate mailing list, I switched to the Command pattern. Any access to server resources (such as the database) is done in the execute() method of a subclass of Command. The GUI code contains an Application class that returns the current CommandProcessor that can execute a command. Two tier systems have a LocalCommandProcessor that executes the command directly. Distributed systems have a RemoteCommandProcessor that passes the command to a ServerCommandProcessor EJB for execution on the server. This has given me a handy place to add additional information to each call, such as the logged in user. The Round Trip Client creates a command, loads it with parameters and executes it thru the CommandProcessor The command is serialized and sent to the server. It's readObject method is called which creates the cache for the command execution on the server. Any domain objects passed with the command are then resolved in this new cache via their readResolve method. The command executes. The database is accessed and any data loaded is resolved thru the cache. Any results to be returned to the client are stored in instance variables in the command. The command object is returned to the client. When the domain objects are deserialized on the client, their readResolve method resolves them with the client side cache. It's [...]

Goodbye to Hibernate

Mon, 26 Apr 2004 13:22:38 -0400

I'm in the progress of ripping Hibernate out of our application. I've been using it since pre 1.0 and we have close to 50 classes mapped now. Here's why it had to go:

1) Our data model is messed up. We had some relations where the key fields in a foreign key could not be mapped. This would have required custom EntityPersisters and such. Not something I wanted to deal with.

2) Startup time for Hibernate is way to slow. Our app needs to run as both a thick client app and loading the mapping for those 50 classes on our Sales Reps machines was taking 30 secs. This was unacceptable and it would have been worse since we'd have 350+ classes mapped when finished. The Hibernate folks have been very adamant that the mappings are parsed at start up, so we're out of luck.

It's taken about a week to replace Hibernate. I've made some handy utility classes to generate SQL plus written some hand coded SQL.

It's actually turning out to be a good thing from the domain design standpoint. I've been able to remove a number of classes that were just there to make Hibernate happy. So far, it has reduced the number of domain classes by 1/3rd.

Adaptive Server Anywhere IP Address

Mon, 26 Apr 2004 13:21:46 -0400

Wow...I wanted to make an entry and JRoller is actually working.

Here's a quick and dirty solution for obtaining the server address of an Adaptive Server Anywhere 7 database.

I have a Sybase Adaptive Server Anywhere database. My program is installed with an ODBC connection. The server could be a local engine or a server engine.

I want to use Sybase's JDBC but that needs a server address. I have no way of knowing the server address when I need to connect.

1) Make sure Java is installed in your database.
2) Make a JDBC-ODBC connection to the database. The ODBC driver will find the database and start the engine if it's local.
3) Issue the following SQL command:

select cast( as varchar) as address from dummy

4) Connect to the database using Sybase's JConnect JDBC driver
5) Close the JDBC-ODBC connection

This is so much simpler than the other two options:
1) Create a DLL to get the machine IP address, deploy it with the server and map an external stored procedure
2) Create a JNI method to call the db_locate_servers

If you can use ASA8, there is a new database property for the server ip address.