Bernie's Blog A confusing concoction of Java, mobile devices, technology and photography

27Jan/100

An Android App In 8 Hours

Inspired by the duo that whipped up an iPhone application within a single weekend, I attempted an Android application within a day. Didn't succeed though - last count there are still 3 open bugs. But what I did manage to do was get a beta out for my friends at CodeAndroid Malaysia to test. A few hours after that, it was in SlideMe, with major bugs fixed.

The application is called - for the lack of a better name - KL Traffic Cam. It's part of a bigger project to provide an Android client for ITIS but due to time constraints, I came up with this. The application is free - as in beer and speech. Yes, you can get it at no cost at SlideMe and checkout its sources from Google Code.

KL Traffic Cam is a community effort by CodeAndroid Malaysia, developed and maintained by your truly. Read more at CodeAndroid Malaysia's blog.

Tagged as: No Comments
8Jan/101

Bashing Bash

Despite being on Linux for quite many years now, I've always come to regard bash (and bash scripting) as somewhat of an arcane magic. No idea why though, just is. To me, it's even scarier than C++ (but that's given since there were 2 semesters of C++ back in school). True enough, a few months back, there was this tiny bit of thing I needed to do in bash and I sucked at it.  Specifically, I was modifying (and fixing) someone else's script. Not fun. Got it to do what I needed it to do, but re-evaluating how certain things were done, I'll be happy if the script is forever buried.

Not any more. Thanks to a few articles over at IBM DeveloperWorks. No idea why I never came across these very useful articles before. The 3-part articles titled 'Bash By Example' (part 1, part 2, and part 3) helped tremendously in helping me understand basics of bash scripting. I'm pretty confident now that I'll be able to rely on bash to do many simple tasks that Java is overkill for.

Also some neat stuff on bash itself, see 'Bash Help'.

Makes one wonder if bash is so easy and useful, maybe the other scripting languages (ruby, python) is worth exploring seriously too. Hmm...

Filed under: Programming 1 Comment
15Dec/090

Eclipse Hudson Plugin

Context - Continuous Integration (CI) is a must. And Hudson is a free, decent, and quick to setup CI server.

To get Hudson into Eclipse - there's a plugin. The recommended way of installing is of course, via the plugin's update URL - http://hudson-eclipse.googlecode.com/svn/trunk/hudson-update/.

After installing it, you'll need to configure it:

Screenshot-Preferences

Once that is out of the way, you'll get this:

Screenshot-Java - Hudson browser - Eclipse

12Dec/090

Guice or Spring?

Just today, someone mentioned that because Spring already does what Guice does (and more, I might add) that I should stick to the latter. I beg to differ. Each has its own purpose, I wouldn't put these 2 in the same league.

Spring is almost a complete container. From security, a web MVC model, batch framework, persistence, JMX, scheduling, web services and many more, Spring offers (or is able to piece together) an almost complete stack to build enterprise applications. In other words, it's a JEE competitor. Its selling point has always been as a lightweight enterprise stack anyway.

Guice on the other hand is a lightweight DI enabler, so to speak. It offers to take away DI code that a developer could otherwise write themselves. This is probably a gross over-simplication but that's how I see it. When I want DI or AOP but I don't want the whole she-bang (and I don't want to do DI manually), Guice is the solution. On the other hand, if I'm looking to develop enterprise software, I could use Guice, but Spring offers so many bundled services that it's hard to ignore.

I like how Guice encourages constructor injection (which, along with final fields, encourages immutability) and that it returns new instances by default - both of which should allow better performing apps when paired with powerful hardware (read: multi-core friendly). I also like how Guice encourages thinking of applications in Modules, its promotion of testability and its potential reusability. I'm a seasoned Spring developer but it was Guice that really made me step back and think about DI, testability and modularity.

After a few weeks of implementing a small library in Guice, it seems there's no turning back. For non-trivial stuff, there's Spring but for everything else, Guice may be the better choice for me. At the end of the day, Guice is yet another tool under my belt. To dismiss it entirely because I already know Spring is just foolish (even if I've been using Spring for 2 years). Of course, I'll also keep my eye on the recently announced JSR that will bring DI to standard Java.

Guice and Spring are but tools. It's DI, AOP and testability that I need.

3Dec/095

Google Guice @Provider Gotcha

Note: Best read after some background reading on Google Guice and dependency injection.

I spent many hours pouring through my codes to resolve this so I'm posting this as a guide to others.

Scenario:

Google Guice allows Providers to be defined, either using the @Provider annotation or by implementing the Provider interface. To those new to Guice, here's a simple explanation on providers:

When you need code to create an object, use an @Provides method

In other words, when you need to inject an object that needs some sort of setup code, or when you need to customize what is injected, you resort to using a Provider. Here's a code snippet that injects a chain of handlers (read: Chain of Responsibility pattern):

@Provides
	private ErResponseHandler provideResponseHandlers() {
		// builds the handlers manually - chain of responsibility pattern
		ErResponseHandler handler = new InactivateAccountResponseHandler(
				new UsageAuthRateChargeResponseHandler());
		return handler;
	}

And this is BaseResponseHandler - a base class which implements ErResponseHandler.

public abstract class BaseResponseHandler implements ErResponseHandler {

        @Inject
	protected XmlBinder xmlbinder;

	public BaseResponseHandler() {
	}
	private ErResponseHandler next;
	public BaseResponseHandler(final ErResponseHandler nextHandler) {
		this.next = nextHandler;
	}
	public final boolean start(final ErResponse response) {
		boolean handled = this.handleResponse(response);
		if (next != null && !handled) {
			next.start(response);
		}
		return handled;
	}
	public abstract boolean handleResponse(ErResponse resp);
}

Everything seems to be in order, right? Straightforward dependency injection of xmlbinder, except of course, this does not work. Xmlbinder is always null. The problem is that once you take over the job of providing your own objects to be injected, injection doesn't work automagically any more. You'll have to wire up your objects manually too.

Solution:

The provider method has to be changed to:

@Provides
        //XmlBinder has been bound using the application Module
	private ErResponseHandler provideResponseHandlers(XmlBinder xmlbinder) {
		// builds the handlers manually - chain of responsibility pattern
		ErResponseHandler handler = new InactivateAccountResponseHandler(
				new UsageAuthRateChargeResponseHandler());
		handler.setXmlBinder(xmlbinder);
		return handler;
	}

Of course, the BaseResponseHandler class now has to set the xmlbinder accordingly:

public abstract class BaseResponseHandler implements ErResponseHandler {

	protected XmlBinder xmlbinder;	

	public BaseResponseHandler() {
	}
	private ErResponseHandler next;
	public BaseResponseHandler(final ErResponseHandler nextHandler) {
		this.next = nextHandler;
	}
        public void setXmlBinder(final XmlBinder binder) {
		this.xmlbinder = binder;
		if (next != null) {
			next.setXmlBinder(binder);
		}
	}
	public final boolean start(final ErResponse response) {
		boolean handled = this.handleResponse(response);
		if (next != null && !handled) {
			next.start(response);
		}
		return handled;
	}
	public abstract boolean handleResponse(ErResponse resp);
}

Unfortunately, Guice's documentation mentions this only in passing:

Dependencies can be passed in as parameters to the method. The injector will exercise the bindings for each of these before invoking the method

It should really be phrased as

Dependencies must be passed in as parameters to the method. Only then will the injector exercise the bindings for each of these before invoking the method.

1Dec/093

Replacing conventional loops with Closures in Java 6

A useful way to promote a low-level code reuse is to use Closures. Think of it as writing generic functions that can be passed around in method calls.

Here's a code snippet that replaces a loop with a Closure:

Closure buildNode = new Closure() {
        //do processing in execute method
	public void execute(final Object obj) {
		nodes = new ArrayList();
		NodeBuilderType builderType = (NodeBuilderType) obj;
		NodeBuilderStrategy strategy = strategies.get(builderType
				.getClass());
		if (strategy == null) {
			throw new NodeBuilderException(
					"No strategy found for Node type:" + builderType);
		}
		nodes.add(strategy.build(builderType, document));
	}
};
//runs a 'for' closure
ClosureUtils.forClosure(builderTypes.size(), buildNode);

Commons Collections also provides utility classes which allows for Closures to be very useful for Collections processing. Here's one that applies a Closure on a Collection:

//define your closure
Closure appendChild = new Closure() {
        //do processing in execute method
	public void execute(final Object obj) {
		Node child = (Node) obj;
		usageAttr.appendChild(child);
	}
};
//executes appendChild against nodes
CollectionUtils.forAllDo(nodes, appendChild);

For more information, look at Apache's Commons Collections. Credit goes to Chris Shayan for sharing this a few weeks back. Update: I'll have to say that this way of achieving closures in JDK<7 is a hack, and feels like a hack but it's one of the solutions available. I'm still eagerly waiting for JDK to allow a more 'native' closure.