Jakub Korab
Tech, Opinion, and Doing Stuff

NASA Open Source Bug Detection Software

April 29th, 2005

NASA have announced the open-sourcing of a system called Java Pathfinder (not the rover). The idea is that it goes over every execution path in a Java program and detects problems such as deadlocks, NullPointerExceptions and the like. From the site, the system seems like it has room to grow – it can handle sources of around 10,000 lines of code, and is limited in its reach into libraries like java.io. Who knows where it thing could go with wider input. I’d love to be able to say that my code was checked by systems developed by NASA – what credibility! :)


Filed under: none | No Tag
No Tag
April 29th, 2005 19:28:00

Dependency Injection with Spring and Struts

April 29th, 2005

A couple of phrases have been getting mentioned lately around the tech sites: Dependency Injection (DI) and Inversion of Control(IoC) – both terms refer to the same thing. Fuzzy terms that you read when you’re looking up something else and bleep over. Start paying attention – this stuff is going to make your life so much easier, that you’ll wonder how you ever did without it.

One of the fundamental principles of good software is orthagonality – or the reduction of dependencies in a system. It’s a good practice to follow, as one of the things you get are components that can be tested easily. Better tested systems translate directly into going home early (or at least not working on weekends), happier clients and more business (or just moving on to other projects).

Dependency Injection is about having a container (don’t panic, it’s not some huge J2EE monster) provide you with components that your classes depend on at runtime by invoking methods on your classes and passing in the dependencies. Your components concentrate on doing their business, and rely upon the container to do its thing (manage transactions, inject aspect code, whatever…). I hope that by showing what this can do you’ll see the potential benefits for yourself.

Why is this important and why should you care? Your classes are plain JavaBeans (POJOs) that can be easily tested using JUnit in your IDE. Need to test a business class that relies on database access objects? No problem – mock up your DAO, and pass it to the business object in the test class’ setUp() method. The best thing is that there is no dependency on foreign APIs, no interfaces to implement – just code, configure and off you go.

Rather than doing some crappy abstract example using two beans, I’m going to make it more realistic by showing you how you would do DI in a Struts application. To this end I’m going to use a DI container, called Spring. The Spring micro-container will manage the lifecycles of all of our objects, and hook the application up (though that’s nowhere near all of the things that it can do, but you can read the documentation for that). We could use other micro-containers like PicoContainer (a 76k JAR!), and it would just be a case of rewiring the configuration – our components are completely oblivious to the existence of the container.

The test application will be typical of a standard web app – a data tier, a business tier and a web tier. I won’t go through putting in a database etc, because it just confuses the issue – and I hate reading stuff that does that, so I won’t put others through it. I’ll start from the bottom and work my way out to the web tier. I am going to use interfaces for all of our major components. It’s best practice anyway, as we can easily switch between implementations, meaning that at test time we can hook in mock objects.

What you’ll need up front:

  • an understanding of Struts and web apps in general
  • a servlet container
  • a copy of Struts (I have used version 1.1, because I already had it lying around)
  • Ant – you’ll need this to build Spring

This example is not going to actually do much, it’s just a glorified hello world – sorry to disappoint. But it will show you the plumbing you need to do to start using this in your Struts apps – AND I’ve actually checked that it works! Cut and paste out of my IDE…

The data tier,
MyDao.java

package test;

/** * Data tier interface. */public interface MyDao { public String saySomething();}

MyDaoImpl.java

package test;

/** * Implementation of the data tier interface. */public class MyDaoImpl implements MyDao { public String saySomething() {  return this.getClass().getName() + ":Hello"; }}

Now for the business tier,
MyBusinessService.java

package test;

/** * Business tier interface. */public interface MyBusinessService { public String saySomething();}

MyBusinessServiceImpl.java

package test;

/** * Implementation of the business tier interface. */public class MyBusinessServiceImpl implements MyBusinessService { private MyDao dao;

 public void setDao(MyDao dao) {  this.dao = dao; }

 public String saySomething() {  if (dao == null) {   throw new IllegalStateException("null dao");  }  return this.getClass().getName() + ":Hello" + "\n" + dao.saySomething(); }}

This is where it gets interesting. Normally at this point we would have created a DAO ourselves using either the new keyword, or a factory class. Not so here… The container make sure that we get class that implements the MyDao interface by calling the setter. You can call the set method anything you like, it must just start with set – standard JavaBeans conventions. This is called setter injection – Spring also supports constructor injection, which means the container will pass in the dependencies when it instantiates the object, but I won’t cover it.

If you’re guaranteed that the setter will be called, why did I put in a null check? Can’t be too careful.

And finally, our Action class:
MyAction.java

package test;

import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;

/** * Spring-managed struts action. */public class MyAction extends Action { private MyBusinessService businessService;

 public void setBusinessService(MyBusinessService businessService) {  this.businessService = businessService; }

 public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,   HttpServletResponse response) {  if (businessService == null) {   throw new IllegalStateException("null businessService");  }  String greeting = this.getClass().getName() + ":Hello" + "\n" + businessService.saySomething();  request.setAttribute("greeting", greeting);  return mapping.findForward("continue"); }}

What’s the story here? Our Action class is managed by the micro-container in the same way as our other beans.
Now, let’s display the results of this whole thing:
test.jsp

<%String greeting = (String) request.getAttribute("greeting");response.getWriter().write(greeting.replaceAll("\n", "<br/>"));%>

The interesting stuff happens in our config. This time, I’ll start on the outside.
/WEB-INF/web.xml

<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"  "http://java.sun.com/dtd/web-app_2_3.dtd">  <web-app>

 <servlet>  <servlet-name>action</servlet-name>  <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>  <init-param>   <param-name>config</param-name>   <param-value>/WEB-INF/struts-config.xml</param-value>  </init-param>  <init-param>   <param-name>debug</param-name>   <param-value>2</param-value>  </init-param>  <init-param>   <param-name>detail</param-name>   <param-value>2</param-value>  </init-param>  <load-on-startup>2</load-on-startup> </servlet>

 <servlet-mapping>  <servlet-name>action</servlet-name>  <url-pattern>*.do</url-pattern> </servlet-mapping>

 <welcome-file-list>  <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>

Nothing unusual here, just a standard Struts ActionServlet configuration.
/WEB-INF/struts-config.xml

<!DOCTYPE struts-config PUBLIC  "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"  "schemas/struts-config_1_1.dtd"><struts-config> <action-mappings>  <action path="/test" type="org.springframework.web.struts.DelegatingActionProxy">   <forward name="continue" path="/test.jsp"/>  </action> </action-mappings>

 <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">  <set-property property="contextConfigLocation"    value="/WEB-INF/applicationContext.xml"/> </plug-in></struts-config>

A couple of points of interest here:

  1. I stuck in the struts-config.dtd file into a shemas directory under WEB-INF.
  2. The action is mapped not to the MyAction class, but to a proxy provided with the Spring framework. This class will provide our Action with a reference to the business tier object.
  3. We load a ContextLoaderPlugIn plugin. This instantiates the Spring micro-container, which in turn parses it’s config file – applicationContext.xml.

And now the last piece of the puzzle:
/WEB-INF/applicationContext.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN//EN"  "http://www.springframework.org/dtd/spring-beans.dtd"><beans> <bean id="myDao" class="test.MyDaoImpl"/>

 <bean id="myBusinessService" class="test.MyBusinessServiceImpl">  <property name="dao"><ref bean="myDao"/></property> </bean>

 <!--   this is where you define your action mappings, ideally this part should be in   another spring-beans.dtd conformant config file called   <our ActionServlet's servlet-name>-servlet.xml   and is added to the contextConfigLocation property of the struts plugin --> <bean name="/test" class="test.MyAction" singleton="false">  <property name="businessService"><ref bean="myBusinessService"/></property> </bean></beans>

We define an object reference called myDao, that references an implementation of the MyDao interface.

We then define an object reference called myBusinessService, that references an implementation of the MyBusinessService interface. On that instance, Spring will call the setDao() method, passing in the myDao object.

Finally, we create a bean reference to our Action class. The DelegatingActionProxy that was mapped to the action in struts-config.xml will find the bean that matched its path and invoke it, passing the myBusinessService object into the MyAction class. By default, objects managed by Spring are singletons, so we have to explicitly tell Spring that we don’t want that behaviour for our Action class.

In Spring, the name and id attributes have the same meaning in a bean definition, but in XML an ID cannot start with the ‘/’ character. The preferred way is to use id, but use name where you have to.

Last bits and pieces to get all of this this running:

  • Set up a web application as above, and add the standard Struts jar files to the lib folder.
  • Get a copy of Spring, extract everything from the zip and run the ant file in the root folder. Copy spring.jar and spring-web.jar to the web application’s lib directory.
  • Configure a context in your container to run the app and fire it up.

When I fired this up by requesting /test.do, I got:
test.MyAction:Hello
test.MyBusinessServiceImpl:Hello
test.MyDaoImpl:Hello

You would think that that was all, but no. Now we’ll do something that really shows of the power of this thing.
AnotherDaoImpl.java

package test;

/** * Alternative implementation of the data tier interface. */public class AnotherDaoImpl implements MyDao {

 public String saySomething() {  return getClass().getName() + ": Here's a class that says something completely different"; }}

Now in the applicationConfig.xml file change:
<bean id=”myDao” class=”test.MyDaoImpl”/>
to
<bean id=”myDao” class=”test.AnotherDaoImpl”/>

Stop the server, redeploy and start up again. Now you should get:
test.MyAction:Hello
test.MyBusinessServiceImpl:Hello
test.AnotherDaoImpl: Here’s a class that says something completely different

Powerful, isn’t it?


Filed under: none | No Tag
No Tag
April 29th, 2005 16:45:00

On emulators, and why you shouldn’t believe everything you read.

April 27th, 2005

Whenever you go through a tech book it’s important to keep in mind that the environment has changed since the time of writing, and therefore the author’s word should not be taken as gospel. After all, that most of this stuff will be out of date in 6 months, if not earlier (that is if this blog even exists by then). In J2ME Games Development the author, Matrin Wells, made a fair remark – that you should not base your games on a simulator environment because:

  • actual processor speed will be different to that on your PC, leading you to think that your game is in better shape than it actually is
  • you will not encounter errors related to exceeding the memory size of the device, either as far as the stack or permanent memory goes

These comments were reasonable a year ago, but I’m not quite so sure now. Sure, you can’t beat having the actual phone in your hand when testing – after all, you may need to rethink the way that the whole control set is put together when those little keys turn out to be too cumbersome for you to actually use your game. The graphics will also look completely different than on your nice, bright 17″ monitor. But surely, the landscape must be changing in respect to the other points – right?

The Netbeans mobility toolkit has some unreal stuff in it, that I was messing around with that tackles some of the issues that Wells raised:

  • clock/processor speed can be configured on a bytecodes per second basis
  • memory/permanent storage can be configured on a kilobyte basis

There are also heaps of things that you wouldn’t even have considered – display rate, network latency, package loss, bluetooth discovery times – you name it, they’ve got it. I’m well and truly impressed. The really coool thing is that you can manage multiple emulators using these settings too. I haven’t tried it, but will do later this week when I start to hook up some vendor sims to play Roadrun on (I was stoked when I found that my version ran pretty well on the various different sims on the mob pack :) .

I’ve been collecting some developer links to the major vendors and am downloading SDKs as I write:

I hit the J2ME licensees page at Sun, and am disappointed that neither Matsushita (makers of the world’s greatest turntable – the Technics SL1200, and also my parent’s old National TV that after 15 years is still going strong in my brother’s room) nor Sagem (the dudes who made my phone, and apparently some satellite navigation systems or something) have developer sites – feel free to correct me if I’m wrong. Oh well, you develop against what you have, so I guess the big 3 it is. Can’t wait to have a play…

I get a bit emotional about the SL1200s – I sorely miss my decks now that I can’t have a good scratch on them. I just hope my beloved baby sister is putting them to good use. The world needs more girl DJs!


Filed under: none | No Tag
No Tag
April 27th, 2005 22:49:00

My wombat runneth over!

April 26th, 2005

Woohoo! My first running mobile game!


Filed under: none | No Tag
No Tag
April 26th, 2005 00:06:00

Is geek humour becoming superfluous?

April 25th, 2005

One of these is real, and the other is a joke. Can you tell which is which?

I have this theory that there’s this bunch of guys at the US Department of Defence whose job it is to surf around joke sites looking for potential weapons programs…


Filed under: none | No Tag
No Tag
April 25th, 2005 15:20:00

Wombat roadkill, or fun with J2ME.

April 24th, 2005

It occurred to me a while back that programming games would be far more interesting than doing business applications all the time – anyone who codes for a living could probably agree that you need to flex the brain muscles every now and again…

So I did some thinking and came to the conclusion that J2ME would be a good platform to get into – it’s still an area where a guy working by himself or with some mates could still do up a fairly decent game in a relatively short amount of time (sub 6 months). No proprietary APIs to buy into, the tools are freely available and the target device is in everyone’s pocket already.

I hightailed off to Sun, went through their reference materials, the CLDC and MIDP docs, downloaded the sample game and went – “Sweet, I can do this.”

The good folks at Netbeans.org have developed a Mobility Pack that you install on top of Netbeans 4.x that comes with pretty much everything you need to get started – debugging, the J2ME runtime and the various baseline Sun simulators. The debugger plugs into the standard mobile simulator architecture (UEI), so you can test the code on sims provided by the various mobile vendors. As well as this it has some excellent utilities to manage issues such as device fragmentation (differing capabilities and resources between phone models).

Most of the mobile vendors have sites with development resources such as proprietary APIs, simulators, code samples and forums. I’ll be adding links to some of these at a later stage, as I get around to using them – it seems there’s no standard for making a phone vibrate :)

To meet my ends I’m currently going through a really good book on the subject, J2ME Games Programming. Having finally beaten through the first couple of chapters that introduce the basic APIs (it always seems to be a hard slog for the first part of any such book), I’m finally on to coding the first sample game, Road Run – a Frogger-inspired game with a wombat. Pretty cool stuff – and a great intro to the problems ahead. What’s the story with hardcoding the sizes of game elements? My first run-in with differing devices – I’m running it against a different sized simulator screen, and it’s all messed up. I love trying to get other people’s code working :P Hopefully tomorrow, the wombat will cross the road without getting run over by cars that appear from nowhere…


Filed under: none | No Tag
No Tag
April 24th, 2005 20:48:00

The sad state of Dublin’s kebabs

April 23rd, 2005

After an evening of stimulating conversation with some of Dim’s work colleagues, we wandered off from the pub with a hankering for kebab (as you do). To our complete digust, we had found that two previously solid joints, Momo’s (which we had both raved about to our mates) and Zaytoon, had replaced their lamb with that processed “meat” that looks like it’s had a severe run-in with an aerator. Cost cutting gone horribly wrong – so much so that we both got our money back at Momo’s: “What do you mean? This is exactly the same meat we have always served!” – sure…

I am thoroughly unimpressed. Aside from the I-can’t-believe-it’s-not-meat issue, the “garlic” sauce is mayonnaise based and has no garlic! Egads, what has the world come to? What Dublin needs is a proper greek souvlaki place with tzaziki so strong that you smell it from the next suburb. Although the whole new-skool souvlaki thing I’ve heard they have going on in Greece, stuffed with chips and ketchup, is all wrong.

They can’t all be dodgy, though. The search continues…


Filed under: none | No Tag
No Tag
April 23rd, 2005 18:40:00

More knowledge that you could ever cram in your head – free!

April 22nd, 2005

MIT are running a program called OpenCourseWare that allows you to go through most of their courses online for free. They are all non-assessable and you will not get any sort of credit for it, but for people like me who can’t get enough information, it’s absolutely insane! All undergraduate and postgraduate course materials, lecture notes, reading lists and assignments (which I swore after university I would never do again) are online. Need to brush up on Techniques in Artificial Intelligence, User Interface Design and Implementation or for that matter Major English Novels?


Filed under: none | No Tag
No Tag
April 22nd, 2005 16:07:00

So what’s this all about?

April 21st, 2005

Firstly an introduction. My name’s Jake, I am a consulting software engineer currently residing in Dublin, Ireland having moved up just under a year ago from Australia with my wife Dim (short for Dimitria).

The idea of this blog was really about dropping in a few bits of technical info that aren’t really available anywhere else or are hopelessly buried in obscure (or just plain long) documentation, that hopefully someone might find useful. It’s also a place for me to collect my own thoughts on various technologies, practices etc. I’m also hoping to whack in a few development framework and tool quickstarts and whatever else I can find time to cram in here. Oh yeah, and just to keep things interesting, I’ll chuck in a few photos of cool shinai bruises and have the occasional off-topic rant about whatever’s got my goat at the time :)


Filed under: none | No Tag
No Tag
April 21st, 2005 16:46:00