Archive for the ‘Uncategorized’ Category.

Thread Police for your Unit Tests

Writing the new ant I stumbled across the problem of test cases leaving threads behind,
after returning control to the runner. My trusted colleague and JUnit Runner expert Mark
Burnett and I, knocked up a quick and dirty junit runner that actually allows you to
spot such a condition.

Consider the following testcode:

@Test
public void losingThreads() throws InterruptedException {
  Thread newThread = new Thread() {
    public void run() {
      for(;;);
    }
  };
  newThread.start();
}

This thing happily spawns a thread and then returns. You get a green test case, but
your IDE might behave somewhat funny as there are still threads open.
To help diagnose these problems we came up with this threadpolicerunner.

If you now annotate your test case like this, to use it:

@RunWith(ThreadPoliceRunner.class)
public class ThreadTest {
    @Test
    public void losingThreads() throws InterruptedException {
        Thread newThread = new Thread() {
            public void run() {
                for(;;);
            }
        };
        newThread.start();
    }
 
 
    @Test
    public void notLosingThreads() throws InterruptedException {
        Thread newThread = new Thread() {
            public void run() {
            }
        };
        newThread.start();
        newThread.join();
    }
 
}

Your runner will give you the following feedback:

Nice, isn’t?

Continue reading ‘Thread Police for your Unit Tests’ »

Poor man’s delegates

When writing Swing applications I find myself quite often in the Situation to write action handling code like this
(Why I do write this kind of code is a different albeit also interesting story):

public class Handler {
    Action doMyThing;
 
    public Handler() {
        doMyThing = new AbstractAction("doMyThing"){
            public void actionPerformed(ActionEvent e) {
                doMyThing();
            }
        };
    }
 
    public void doMyThing(){
        System.out.println("printlning is so my thing.");
    }
}

No this looks ok at first sight. My IDE helps me creating that anonymous inner class and all. But as soon as there are
three or more actions on my presentation model things get really hard to read. C# introduced delegates for this kind of
problem, but what shall the poor Java programmer do?

The thing I tend to ask myself in such situations is, what would I like to write? What of the above code matters? what
is coincidental? So a naïve approach would look like this:

public class Handler {
    Action doMyThing;
 
    public void doMyThing(){
        System.out.println("printlning is so my thing.");
    }
}

I just slashed all the lines, that seem to be technicalities. And I like it. I still can exercise the doMyThing method
in a unit test. And actually it doesn’t take that much to get the thing up and running. We have to do add in a constructor again.
But this one is only O(1) in length:

public class Handler {
    Action doMyThing;
 
    public Handler() {
        ActionReflector.reflectActions(this);
    }
 
    public void doMyThing(){
        System.out.println("printlning is so my thing.");
    }
}

I like this quite a lot. But how does it work. The reflector looks for all the fields of type Action. If they are null
it looks for a method with a matching name. Then it news up a new Action that calls this method and assigns it to the field.
If the method lookup fails an exception is thrown. So as long as the class is instantiated at least once in a unit test
– which is what one might hope for – the naming convention will actually be enforced.

Here is a a more complex example which illustrates the benefits of this approach.

public class Handler {
    Action doMyThing;
    Action doThisOtherThing;
 
    Action manualAction;
 
    public Handler() {
        manualAction = createManualAction();
        ActionReflector.reflectActions(this);
    }
 
 
    public void doMyThing() {
        System.out.println("printlning is so my thing.");
    }
 
    public void doThisOtherThing() {
        System.out.println("printlning is also this other thing.");
    }
 
 
    private Action createManualAction() {
        return new AbstractAction("") {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Doing a manual thing.");
            }
        };
    }
}

The manualAction field is assigned, before the reflector is run. This is quite handy if you just want to delegate to another
handler. So you combine the old and the new way easily.
If you forget to initialise it, the reflector will fail and tell you the method is missing.

Of course this approach can be extended. One thing I do is to have a second method, that indicates
whether the action is enabled. Generally speaking you could use this to implement multi-method interfaces by
having a naming convention for each method on the interface.

This niceness has to be paid with some infrastructure code, which is a bit ugly – mostly due to
all the declared exceptions in the java reflection.

In essence this gives you a delegate. It works very well for me. Even though you don’t have compile time security, it will
blow up as soon as you new your object up, if you get the spelling wrong.

Holiday in Spain

Very recently I had the pleasure of exploring Spain. Here are some of my Impressions:

I was climbing a bit on the Peñon d’Ifach (the spelling is probably wrong):

Futhermore I was seeing Spanish supermarkets. Luckily I stumbled across the following packaging (soy extra grueso).

I also went to see my old flatmate Andy from Hanover Gardens in Alicante.

Which is a very charming place with good mochitos.

Of course there was Barcelona. Capital of the Katalans. And famous katalan Musicians and so forth as the guide on the bus tour kept explaining.
This is good old Columbus (The other day I went down to Trafalgar Square to see Nelson, who gave the Spanish a bit of a beating up – ;-) ).

There was also the Fiesta Major in Gracia.

And as you can tell from the following image I had a really good time. I also saw loads of other stuff, but that was more or less the usual: the beach, Gaudi, and all.

Verdict: Spain is a cool place.

A Screen Camera in Java

Today I wrote a little class
that allows to repeatedly capture the screen content and write the result to a flash file.
It created a flash video with one frame per second (this is a bit crude) with one frame per screen shot taken. It is based on JavaSWF2 a nice wrapper around the SWF file format. To run you need to get the JavaSWF2 jarfile. Then you go:

camera = new ScreenCamera(new File("test.swf"));
doStuff();
camera.takeScreenShot();
doMoreStuff();
camera.takeScreenShot();
camera.close();

It might be useful for testing and creating tutorials.

Implementing Custom Quicksilver Actions

As it was a nice London day today – wind, rain, sunny spells and a cosy 15˚C all that, I spent the day with my Mac learning how to get more out of Quicksilver. I was wondering for some time how to implement my own actions. The task at hand was to have a single action that allows me to push files to the dropbox folder on my server out in the internet. So all this thing has to do is to create the right command line call. Unfortunately there is no way easy way just to add command using placeholders (or none that I am aware of).

So what you have to do to write an Actions is to write an AppleScript (which has a very idiosyncratic syntax, but feels a bit TCLee ) and put it into the right folder, something like /Users/USERNAME/Library/Application Support/Quicksilver/Actions/MyAction.scpt

So this is the thing I hacked up. It uses growl to notify the user, when the transfer is completed. Unfortunately it doesn’t display an error on failure. I would have to spend more time with AppleScript, but perhaps one of the readers comes up with a solution.

on open these_items
   repeat with i from 1 to the count of these_items
      set target to "user@host.com:/home/user/dropbox"
      set filename to the quoted form ¬
         of the POSIX path of (item i of these_items)
      set theResult to ¬
         do shell script "scp -q " & filename & " " & target
      growl((filename & theResult))
   end repeat
end open
 
 
on growl(theText)
   tell application "GrowlHelperApp"
      set the allNotificationsList to ¬
         {"Test Notification", "Another Test Notification"}
         set the enabledNotificationsList to ¬
            {"Test Notification"}
            register as application ¬
               "Growl AppleScript Sample" all notifications allNotificationsList ¬
                default notifications enabledNotificationsList ¬
                icon of application "Script Editor"
 
            notify with name ¬
               "Test Notification" title ¬
               "Drop done" description ¬
               theText application name "Growl AppleScript Sample"
	end tell
end growl

Useful links: QS wiki on scripting, QS google group

Verdict: QS rocks!

Don’t get knocked up and drink

I found this on my beer bottle the other day:

It is consistent with my previous observations about the british being fond of being patronised.

To Hell with Virtualisation – Updated

These days virtualisation seems to be all the rage. There are some benefits to it. It’s a way to increase the utilsation of your hardware just as pipelining increases the utilisation of the processor’s execution units. But as pipelining it comes at a price. You might increase the throughput, but the latency gets higher. Furthermore the response times become highly random, as they now depend on all the other users on the machine.

Especially in the context of development this poses a few risks. I have been working in environments with the build servers using virtual machines and shared database servers. This leads to variable build (and test) times – usually not shorter ones though!

It leads developers to ignore the time the code takes to execute, because there is no reliable feedback and all problems tends to be blamed to the environment or the database. In the worst case it leads to integration tests being ignored and abandoned, because they fail for timeouts, which result from dead slow code and unreliable system performance.

It is often said that code is to be read by humans. This is true. But it is also true and to be borne in mind, that code is run on machines. Virtualisation is clearly obscuring this fact.

Update: Dale was making the interesting point, that virtualisation is giving you a more controlled environment, because you can save your virtual machine and go back to defined points. This seems like a good thing and makes things easier in the first place. I think this is a double edged sword. In my experience you actually start incurring dependencies to that very environment. In my opinion software should be written in a way that it manages and contains it’s state. I have seen projects where you had to install database servers into the operating system (registry!). Then install stuff into the database server. Of course you also needed an application server. Everything needs to be configured. Then you run another obscure unscriptable utility to get your test data into the database. There is a huge temptation just doing these things manually and then save a snapshot of your vm. The actual problems like the use of side-effect-laden tools, resource-leakage during runtime, and poor setup-scripts remain untacled.

Writing a system that can’t work without a reboot is not a good practice. It should be a good citizen in the operating system or on the virtual machine it runs on.

New Home in Holloway

After an intense Month of flat-hunting and another month of waiting for broadband I am now fully equipped in my new Holloway house-share. My current commute is about the same as from the oval. But lets show some pictures (note that most of the stuff that is lying around is actually mine).

There is a big dining table:

And a kitchen too:

Which leads directly to our lovely fully BBQ-equipped garden:

Now we go upstairs and have a look at my generous 10m2 (the desk and the sheving over the bed has been custom made by the current incumbent):

There is also a nice view of the garden from my room:

We are just seconds away from all the shopping opportunities of Holloway Rd and Seven Sisters Rd:

Overheared in the Office

“This year I really gonna quit being a fat guy.”

Some Pictures

As I moved in two weeks ago some pictures of the new place are now clearly required. First there is my room, which is really bigger than the old one.

There is also a nice up-to-date kitchen…

..as well as a drawing room.

The door to our flat:

And a view from the balcony, straight over to the gasworks:

As a final goody I have got a pic of the washing machine, before I cleaned it a bit: