Archive for the ‘ Software ’ Category

SiteMesh 2.1 released

SiteMesh 2.1 has been released. The main changes in this release:

* Out-of-the-box support for writing decorators in Velocity.
* Performance improvements.
* Numerous bug-fixes, particularly container-specific issues.

Read an introduction and then download.

http://www.opensymphony.com/sitemesh/

Agile Development Conference coming up…

ADC in Salt Lake City is just around the corner. I’ve heard nothing but good reports from the previous events so I’m checking it out. The line up looks great.

Apparently there are still spaces available. If you’re going, get in touch and we can meet up.

Oh and remember to come along to the personal practices session.

Unit Testing Asynchronous Code

I try to avoid using code that instantiates threads from unit-tests. They’re awkward to write, brittle and I would rather extract the controlling thread, using the test as the controller. However there are times when it’s unavoidable.

Here’s an example. A PriceFinder is a class that goes and retrieves a price for a symbol asyncronously, returning immediately. Sometime later it receives a response and performs a callback on a handler. I’ve left out the implementation of how it actually does this (maybe a web-service, database call or JMS message).

public class PriceFinder {
 public void findPrice(String symbol, PriceHandler handler) { ... }
}

public interface PriceHandler {
 void foundPrice(Price price);
}

To test this, a handler can be used from the test case that records what is passed in. The test can then wait for a specified time and assert that the correct result is received. If the asyncronous code does not complete within the specified time, the test will fail (suggesting the code is either running very slowly or is never going to complete).

public class PriceFinderTest extends TestCase {

 private PriceFinder finder = new PriceFinder();
 private Price receivedPrice;

 public void testRetrievesAValidPrice() throws Exception {
  finder.findPrice("MSFT", new PriceHandler() {
   public void foundPrice(Price price) {
    receivedPrice = price;
   }
  });

  // Smelly!
  Thread.sleep(2000); // Wait two seconds.
  assertNotNull("Expected a price", receivedPrice);
 }

}

However, this sucks as it will slow your test suite right down if you have loads of tests using Thread.sleep().

A less time consuming way to do it is by using wait() and notify() on a lock. The handler notifies the lock and the test waits for this notification. In case this notification never happens, a timeout is used when calling wait().

public class PriceFinderTest extends TestCase {

 private PriceFinder finder = new PriceFinder();
 private Price receivedPrice;
 private Object lock = new Object();

 public void testRetrievesAValidPrice() throws Exception {
  finder.findPrice("MSFT", new PriceHandler() {
   public void foundPrice(Price price) {
    receivedPrice = price;
    synchronized(lock) {
     lock.notify();
    }
   }
  });

  synchronized(lock) {
   lock.wait(2000); // Wait two seconds or until the
   // monitor has been notified.
   // But there's still a problem...
  } 
  assertNotNull("Expected a price", receivedPrice);
 }

}

This optimistic approach results in fast running tests while all is good. If the PriceFinder is behaving well, the test will not wait any longer than the PriceFinder takes to complete its work. If PriceFinder has a bug in it and never calls the handler, the test will fail in at most two seconds.

However, there’s still a subtle issue. In the case that the PriceFinder is really fast, it may call notify() before the test starts wait()ing. The test will still pass, but it will wait until the timeout occurs.

This is where threading and synchronization get messy and beyond me. Doug Lea has a nice little class called Latch in his concurrency library (available in JDK 1.5 as CountDownLatch). A latch can only be locked once, once released it will never lock again.

public class PriceFinderTest extends TestCase {

 private PriceFinder finder = new PriceFinder();
 private Price receivedPrice;
 private Latch latch = new Latch();

 public void testRetrievesAValidPrice() throws Exception {
  finder.findPrice("MSFT", new PriceHandler() {
   public void foundPrice(Price price) {
    receivedPrice = price;
    latch.release();
   }
  });

  latch.attempt(2000); // Wait until the latch is released
  // or a timeout occurs.
  assertNotNull("Expected a price", receivedPrice);
 }

}

That’ll do it.

How to host your own private CVS repository

Here’s a quick way to host your own remote private CVS repository, accessible via SSH.

All you need is an SSH enabled shell account on a UNIX box that has the CVS client installed. If the box doesn’t have a cvs client installed, you should be able to download a binary (or compile source) and place it in your local path. If you have webspace somewhere, chances are you’ve got everything you need.

Assuming, the server is foo.myserver.com, your username is myuser and your home dir on that server is /home/myuser, here are the steps:

* SSH to foo.myserver.com
* mkdir /home/myuser/cvsroot
* cvs -d /home/myuser/cvsroot init

Now, you can access your private CVS repository from anywhere using the CVSROOT :ext:myuser@foo.myserver.com:/home/myuser/cvsroot.

ASP.NET MasterPages and SiteMesh

It’s nice to see the SiteMesh approach catching on… ASP.NET 2.0 includes a features called MasterPages, which is a kind of hybrid of SiteMesh and Tiles .

Specifying a master page with ASP.NET is similar to how you do with SiteMesh – a plain HTML page containing common look and feel, with placeholders for the actual content. However with master pages, you need to change the actual pages serving the content to map fragments of content back to the place holders in the master page. This adds yet more noise to typically already noisy ASP.NET pages – a minor downer.

Overall, it’s looking pretty promising. A nice bonus is how the page designer in VS.NET will render your master page when editing content pages, but grey it out. Look.

Anyhoo… I’ll be demonstrating SiteMesh.NET and talking about MasterPages at the Bangalore .NET User Group tomorrow (Thursday) night. If you’re in the area, please drop on by.

Announcing XStream: Java to XML serialization, and back again.

XStream is a simple library to serialize objects to XML and back again.

Features

  • Ease of use. A high level facade is supplied that simplifies common use cases.
  • No mappings required. Custom objects can be serialized without need for specifying mappings.
  • Performance. Speed and low memory footprint are a crucial part of the design, making it suitable for large object graphs or systems with high message throughput.
  • Clean XML. No information is duplicated that can be obtained via reflection. This results in XML that is easier to read for humans and more compact than native Java serialization.
  • Requires no modifications to objects. Serializes internal fields, including private and final. Supports non-public and inner classes. Classes are not required to have default constructor.
  • Full object graph support. Duplicate references encountered in the object-model will be maintained. Supports circular references.
  • Integrates with other XML APIs. By implementing an interface, XStream can serialize directly to/from any tree structure (not just XML).
  • Customizable conversion stategies. Strategies can be registered allowing customization of how particular types are represented as XML.
  • Error messages. When an exception occurs due to malformed XML, detailed diagnostics are provided to help isolate and fix the problem.

http://xstream.codehaus.org/

OT2004 : Delegation in Java

Ivan Moore is blogging about it here.

OT2004 : Taming the Tiger (Java 1.5)

This session was presented by Benedict Heal, and he was brilliant; concise, clear, humourous and extremely chilled out. Even the fact that Josh Bloch was listening in on his presentation didn’t phase him.

Most of the new Java 1.5 features are already widely known. Generics, annotations, auto-boxing, enums, syntactic sugar, yada yada yada.

Some things that caught my eye:

* -Xlint : a compiler flag to warn you when your code can be improved to take advantage of new features such as generics.
* Generics are not available at runtime (unlike C#).
* Use of generics all over the API, not just collections. For example, Class is a genericised type, so newInstance() returns the correct type.
* List<MyThing> cannot be given a List<ExtendedMyThing>. Makes sense really as otherwise you’d be able to add things that it shouldn’t allow.
* Genericised types can be constrained to only allow certain type. class Blah<T extends MyThing>.
* Wildcards allow even more flexibility: List<? extends MyThing> list = new ArrayList<ExtendedThing>() // valid.
* Or this: List<? super ExtendedThing> list = new ArrayList<MyThing>(); // valid
* Generics are complicated :)
* Annotations can be specified as source level, class level (available for inspection by class loader) or runtime level (available through reflection).
* Variable parameters to a method. Defined like this: printf(String format, Object… args). The three dots are part of the syntax! Called like this: out.printf(“Blah % blah % blah”, 44, “hello”, someObject). Note autoboxing comes into play too.

It’s only a shame there isn’t a feature such as the anonymous delegate in C#… now that is real power. Rock on Java 1.8.

OT2004 : Personal Practices Map

In the evening, everyone had a chance to run a Birds of a Feather session. I thought I’d give it a go and repeat the session from XtC last year.

It was a chance to talk to other developers about the little things we do that help guide development.

It was a calm and enlightening session. I felt I learned a lot from the attendees. Techniques that I would probably otherwise never know about unless I actually paired with them.

I look forward to doing this again at ADC.

Romilly generated a topic map from the results: (click here)

OT2004 : Elegant Implementation of Null Objects

Since Dan and I have both been working together again (2 years at ThoughtWorks) and since I moved into a house less than ten minutes walk from his, we very rarely see each other. So it was good fun to have a geeky catch up session and play with some code.

Something Dan showed me:

interface Something {
Something NULL = (Something)Null.object(Something.class);
// more stuff…
}

The Null class is a simple dynamic proxy that will return an immutable null object that does nothing. Methods that return values will return default primitives (0, false), empty arrays or more dynamic proxies.

So at any point in the code you can call Something.NULL to get the null implementation.

Nice! (Dan, upload it somewhere!)
Update: He did – http://proxytoys.codehaus.org/