Runtime-replace implementations with Roboguice in functional tests

At work we’re heavily depending on Unit and Functional Testing for our current Android application. For Unit testing we’ve set up a pure Java-based project that runs on [Robolectric]( to provide a functional Android environment and we also added [Mockito]( to the mix to ease some code paths with spied-on or completely mocked dependencies. [Moritz Post wrote a comprehensive article]( how to setup this – if you have some time, this is really worth a read.

Now our functional tests are based on what the Android SDK offers us – just that we’re using [Robotium]( as a nice wrapper around the raw instrumentation API – and until recently I thought it would not be possible to screw around much with an unaltered, but instrumented application on runtime. But while I was reading through [the Android Testing Fundamentals]( I stumbled upon one interesting piece:

With Android instrumentation […] you can invoke callback methods in your test code. […] Also, instrumentation can load both a test package and the application under test into the same process. Since the application components and their tests are in the same process, the tests can invoke methods in the components, and modify and examine fields in the components.

Hrm… couldn’t that be used to just mock out the implementation of this one REST service our application uses? Yes, it could! Given the following implementation

public class RequestManager {
    public <I, O> O run(Request<I, O> request) throws Exception {

(where the `Request` object basically encapsulates the needed request data and Input / Output type information)

it was easy to create a custom implementation that would return predefined answers:

public class MockedRequestManager extends RequestManager {
    private Map<Request, Object> responses = new HashMap<Request, Object>();
    public <I, O> O run(Request<I, O> request) throws Exception {
        Object response = findResponseFor(request);
        if (response instanceof Exception) {
            throw (Exception) response;
        return (O) response;
    public void addResponse(Request request, Object response) {
        responses.put(request, response);

Now that this was in place, the only missing piece was to inject this implementation instead of the original implementation. For that I created a new base test class and overwrote the `setUp()` and `tearDown()` methods like this:

public class MockedRequestTestBase extends ActivityInstrumentationTestCase2 {
    protected Solo solo;
    protected MockedRequestManager mockedRequestManager = new MockedRequestManager();
    private class MockedRequestManagerModule extends AbstractModule {
        protected void configure() {
    public MockedRequestTest() {
    protected void setUp() throws Exception {
        Application app = (Application) getInstrumentation()
            app, RoboGuice.DEFAULT_STAGE,
                .with(new MockedRequestManagerModule()));
        solo = new Solo(getInstrumentation(), getActivity());
    protected void tearDown() throws Exception {

It is important to note here that the module overriding has to happen _before_ `getActivity()` is called, because this starts up the application and will initialize the default implementations as they’re needed / lazily loaded by RoboGuice. Since we explicitely create a specific implementation of the `RequestManager` class before, the application code will skip the initialization of the actual implementation and will use our mocked version.

Now its time to actually write a test:

public class TestFileNotFoundException extends MockedRequestTestBase {
    public void testFileNotFoundMessage()
        Request request = new FooRequest();
            new FileNotFoundException("The resource /foo/1 was not found")
        solo.clickOnView("request first foo");
        assertTrue(solo.waitForText("The resource /foo/1 was not found"));

Thats it. Now one could probably also add Mockito to the mix, by injecting a spied / completely mocked version of the original RequestManager, but I’ll leave that as an exercise for the reader…

Have fun!

Debugging with MacPorts PHP binaries and Eclipse PDT 3.0

You know the times, when things should really go fast and easy, but you fall from one nightmare into another? Tonight was such a night… but lets start from the beginning.

To debug PHP you usually install the excellent [XDebug]( and so did I with the port command `sudo port install php5-xdebug`. After that `php -v` greeted me friendly on the command line already:

PHP 5.3.8 (cli) (built: Sep 22 2011 11:42:56)
Copyright (c) 1997-2011 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2011 Zend Technologies
with Xdebug v2.1.1, Copyright (c) 2002-2011, by Derick Rethans

Eclipse Indigo and Eclipse PDT 3 was already installed, so I thought it should be easy to set up the XDebug debugging option in Eclipse. Under “PHP > PHP Executables” I therefor selected `/opt/local/bin/php` as my CLI version and selected “xdebug” as debugging option.

A first test however showed me that the execution of a test script did not load any module into the PHP interpreter beforehand (for reasons I could only guess, because Eclipse error log kept quite). Looking at the output of `phpinfo()` from my test script and `php -i` from command line showed me the difference: The PHP option “Scan this dir for additional .ini files” was empty when PHP ran inside Eclipse, but was properly set when PHP ran from command line (or in an Apache context).

Asking aunt Google brought up [this issue]( that shed some light into my darkness: The directory where additional modules reside is configured as a compile time option in PHP and defaults to `/opt/local/var/db/php5` on MacPorts and exactly this can be overridden by either calling PHP with `-n -c` options or by setting the `PHP_INI_SCAN_DIR` environment variable.

Having no access to the actual PHP call from inside Eclipse I tried to go down the environment route, but that did not lead to any success. While the variable was recognized as it should on the normal command line (e.g. `PHP_INI_SCAN_DIR= php -i` disabled the load of additional modules), in Eclipse’ run configuration dialog, in the section environment variables, this was not recognized at all. I tried a little harder and configured the variable inside `~/.MacOSX/environment.plist`, logged out and in again, restarted Eclipse obviously, but had no luck either.

The only viable solution I came up with was to place all the single `extension=` and `zend_extension=` entries directly into my `php.ini` and disable the individual `module.ini` files altogether. At least I can now run and debug properly, but this solution is of course far from being ideal – as soon as I add a new PHP module or want to remove an existing, I have to remember to edit the `php.ini` myself.

By the way, I also tried to use Zend’s debugger (and PDT plugin) as an alternative. [While somebody else]( already ranted about that the Zend guys have been unable to provide the Zend Debugger for PHP 5.3 as a standalone download (which hasn’t changed to date), PHP 5.2 debugging worked nicely with [the old Zend PDT plugin](

Of course, none of my needed PHP modules were loaded and I really needed PHP 5.3 support, so I had to follow the same route the other guy did and downloaded all of the ZendServer glory (a 137MB download, yay) just to get the right ``. After extracting the `.pax.gz` archive from the installer package I quickly found it underneath `usr/local/zend/lib/debugger/php-5.3.x/`, copied it to my extension directory and added an ini file to load that one instead, just to find out shortly afterwards that the Zend binary was `i386` only and MacPorts of course compiled everything nicely as `x86_64` – php was of course unable to load such a module.

Well, the moral of the story is – go for Xdebug and don’t loose the track. And, let us all hope that Eclipse PDT is developed further, so the remaining glitches like the one above are fixed.

Exception chaining in Java

If you catch and rethrow exceptions in Java, you probably know about exception chaining already: You simply give the exception you “wrap” as second argument to your Exception like this

try { … }
catch (Exception e) {
throw new CustomException(“something went wrong”, e);

and if you look at the stack trace of the newly thrown exception, the original one is listed as “Caused by:”. Now today I had the rather “usual” use case of cleanup up a failing action and the cleanup itself was able to throw as well. So I had two causing exceptions and I wanted to conserve both of them, including their complete cause chain, in a new exception. Consider the following example:

try { … }
catch (Exception e1) {
try { … }
catch (Exception e2) {
// how to transport e1 and e2 in a new exception here?!
throw e1;

My idea here was to somehow tack the exception chain of `e1` onto the exception chain of `e2`, but Java offered no solution for this. So I hunted for my own one:

public static class ChainedException extends Exception {
public ChainedException(String msg, Throwable cause) {
super(msg, cause);
public void appendRootCause(Throwable cause) {
Throwable parent = this;
while (parent.getCause() != null) {
parent = parent.getCause();

Now I only had to base the exceptions I actually want to chain on `ChainedException` and was able to do this (in fact I based all of them on this class):

try { … }
catch (ChainedException e1) {
try { … }
catch (ChainedException e2) {
throw new ChainedException(“cleanup failed”, e2);
throw e1;

Try it out yourself – you’ll see the trace of `e1` at the bottom of the cause chain of `e2`. Quite nice, eh?

guitone license change

[Guitone](, my little GUI frontend for the [monotone SCM](, is currently licensed according to the terms of the GPLv3+ and was previously – before version 0.8 – licensed under GPLv2+. Newer development however forces me to re-license it again, this time under slightly less restrictive “copyleft” terms, under LGPLv3.

The reason for this is my usage of the [Graphviz library]( to render monotone revision trees. Graphviz is released under EPL (older versions under CPL even), and this license is strictly incompatible to any pure GPL version. I contacted the Graphviz guys and I also contacted the legal affairs support of the FSF and checked the options I had and the result is now that I have to adapt, one way or another. I could either use the “command line interface” of Graphviz or choose another license for guitone. I didn’t want to go the first route, simply because I have a working implementation and because I didn’t want to make slow calls into external binaries, so a new license had to be chosen on my side.

So, starting with the upcoming version 1.0 guitone is licensed under LGPLv3. I contacted the previous contributors of guitone and all parties are ok with the license change, so the actual license change will pop up in the [current development’s head shortly](

Thanks for your interest.

Access the Android menu in VirtualBox on a Mac host

If you’re desperately trying to get the `Menu` button in an [Android x86]( installation working under [VirtualBox]( on a Mac OS X host – whose keyboard of course doesn’t have this “context” / “menu” key Windows keyboards have on the right – you might find the touch-only-device mode in Android x86 handy:

1. Click on the clock in the status bar to enable / disable this mode altogether
2. A swipe from the left to the right emulates the `Menu` button function
3. A swipe from right to left emulates the `Back` button function
4. Simply clicking on the status bar brings you to the `Home` screen


Einführung die Versionsverwaltung mit monotone

[Mathias Weidner]( hat eine deutschsprachige Einführung in die Versionverwaltung mit monotone [veröffentlicht]( Er behandelt darin die Grundlagen der verteilten Versionsverwaltung, die ersten Schritte mit monotone, sowie die täglich anfallende Arbeitspraxis mit einem Versionskontrollsystem. In späteren Kapiteln widmet sich Mathias auch erweiterten Themen, etwa wie monotone auf die individuellen Bedürfnisse des Nutzers angepasst werden kann und liefert weitere nützliche Hinweise für Ein- und Umsteiger von anderen Versionskontrollsystemen.

Das Buch ist [CC BY-SA 3.0]( lizensiert und kann als [Paperback über lulu]( bezogen werden. Eine [Vorversion in PDF-Format]( ist ebenfalls verfügbar; da der Autor die Quellen selbst in monotone verwaltet, sollten auch diese demnächst verfügbar sein.

Vielen Dank an Mathias für seine Bemühungen!

jazzlib – an alternative for reading ZIP files in Java

Java had zip-reading capabilities for a long time, naturally because `jar` files are simply compressed zip files with some meta data. The needed classes reside in the `` namespace and are `ZipInputStream` and `ZipEntry`.

Recently, however, `ZipInputStream` gave me a huge headache. My use case was as simple as

* read the zip entries of a list of zip files (each varying in size, but usually around 20MB)
* skip to the zip entry that has a certain name (a single text file with only two bytes of contents)
* read the contents of this zip entry and close the zip

Doing this for about 25 files took my Pentium D (2GHz) with 3GB of RAM roughly **20 seconds**. Wow, 20 seconds really? I created a test case and profiled the code in question separately with [YourKit]( (which is a really great tool, by the way!):

It got stuck quite a bit in `` – but that seemed to use native code, so I couldn’t profile any further.

So I went on and searched for an alternative of `` – and luckily I found one with [jazzlib](, which provides a pure Java implementation for ZIP compression and decompression. This library is GPL-licensed (with a small exception clause to prevent the pervasiveness of the GPL) and comes in two versions, one that duplicates the single library classes underknees `` (as a drop-in replacement for JDK versions where this is missing) and one that comes in its own namespace, `net.sf.jazzlib`.

After I went for the second version, I restarted my test and it only took about **7 seconds** this time. At first I thought that there must be some downside to this approach, so I checked the timings for a complete decompression of the archive, but the timings here were on par with the ones from `` (roughly 5 seconds for a single 20MB file).

I haven’t tested compression speed, because it doesn’t matter much for my use case, but the decompression speed alone is astonishing. I wonder why nobody else stumbled upon these performance problems before…

Indefero 1.1 released

I’m pleased to announce the immediate release of [Indefero 1.1]( This release features support for another version control system, [monotone](, and comes with tons of smaller improvements and bug fixes.

A full list of changes can be found in the [News]( document.

Many thanks to all the contributors!

mtn-browse 0.72 and accompanying Perl library released

Tony Cooper announced a new release of his [Monotone Browser]( software and also a new version of the underlying [Monotone::AutomateStdio]( Perl library.

Both packages are now compatible with the most recent version of monotone, 0.99.1. Additionally, mtn-browse also supports all the new selector functions introduced in monotone 0.99 and is able to restrict revision and file histories to specific branches.

Many thanks to Tony for his outstanding work! I’ll update the MacPorts packages in a few…

One framework to rule them all

I have a love/hate relationship with PHP; while I have [talked in great length about all the badness]( that comes with it, I still find myself quite often writing and / or contributing to PHP applications. Most of this work was done with [Symfony]( and, to a smaller degree, recently also with a relatively unknown framework called [Pluf](, which is the main building block for [Indefero](, the project and source code management tool I’m contributing to.

The author of Pluf, Loic d’Anterroches, has released a new framework to the wild today and its called [**Photon**]( It got its name from the particle, so naturally the tag line is *”…because nothing is faster than a photon”*.

So you are by now probably asking “Ok, but **why should I care** about that? There are dozens if not hundreds of PHP frameworks out there, they all claim to be fast, so this is probably just a complete waste of time…”

Well, Photon is very different, because it achieves its performance with a break of the traditionally known request-response model: Much like a real **application server** you know from other languages you can process requests asynchronously now in pure PHP, i.e. start and stop processes on request and delegate long-running work for later execution!

PHP developers did all kinds of bad tricks to emulate this stuff in the past. Most of these tricks employ a cache table and a cron entry that regularily executes some PHP script. This is buggy, doesn’t scale well and is of course plain ugly.

I won’t go into more details – just hop over to [](, read the docs and grab the pre-release while its hot!