rapaul.com

A technical blog written by Richard Paul

Meetups in London

Update, I’m now back in Auckland and the meetup scene is alive and well.

One of the great things about London, from a developer’s perspective, is the wealth of meetups going on. Don’t get me wrong, in Auckland we had a few notable meetups including the Auckland JVM Group and the Auckland Web Meetup. But London has more people, more developers & hence more meetups.

Below is a live calendar of the meetups I’m planning on attending,

I’ll try to keep this up to date, so feel free to subscribe to the calendar if you have similar interests (java, javascript, groovy, scala, testing, mocking, android, webOS, html5… anything you see in this blog’s tag cloud).

BDDMockito & Eclipse

On the 23rd of July, Mockito 1.8.0 was released, you can see a full listing of changes in their release notes. One feature that took my fancy was the inclusion of BDD aliases for stubbing an API, instead of using when, the Mockito team now encourage the use of given to bring your tests inline with the BDD style. To illustrate this, here is an example taken from the BDDMockito javadoc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import static org.mockito.BDDMockito.*;

Seller seller = mock(Seller.class);
Shop shop = new Shop(seller);

public void shouldBuyBread() throws Exception {
  //given  
  given(seller.askForBread()).willReturn(new Bread());

  //when
  Goods goods = shop.buyBread();

  //then
  assertThat(goods, containBread());
}

By breaking the test into given, when & then, future maintainers of the tests will more quickly understand which parts of the test relate to setup, exercising the SUT and asserting.

(stealing from Apple’s AppStore ad) What’s great about Eclipse, is that if you want to write a foreach loop, there’s a template for that. If you want to create a unit test, there’s a template for that. Yip there’s an app template for just about anything.

To minimise keystrokes and encourage the use of this style, you can modify the existing Test template as shown below to automatically generate the BDD style comments & statically import the BDDMockito members. To modify the template, navigate to Window > Preferences > Java > Editor > Templates. Click on Test (the JUnit 4 test template) and click edit. Paste in the follow template:

1
2
3
4
5
6
7
8
9
10
11
@${testType:newType(org.junit.Test)}

public void ${testname}() throws Exception {
  // given ${cursor}
  ${staticImport:importStatic('org.junit.Assert.*', 'org.mockito.BDDMockito.*')}

  // when

  // then

}

You are now ready to start writing BDDMockito style unit tests using Eclipse’s template, simply type Test, hit Ctrl+Space and you will be given the following option.

Selecting the option will generate the test method, focus first given to the test name, then to the blank line after // given.

There you have it, a simple Eclipse template to generate your BDDMockito style tests.

Review: Spring Web Flow 2 Web Development

Spring Web Flow 2 Web Development Authors: Markus Stäuble & Sven Lüppken Publisher: Packt Publishing Date of Publishing: March 2009 Sample Chapter: Chapter 4: Spring Faces

Intended Audience

This book is intended for Java web application developers who wish to learn about Spring Web Flow 2. A base knowledge of the Spring Framework and its associated MVC is advised, however most examples in the book provide sufficient detailing of the surrounding technologies and their integration points. This allows the reader to follow the examples without looking up details from other reference sources.

Chapter 1 - Introduction

The first chapter of this book provides a general introduction to Spring Web Flow 2 including some of the basic terminology. For those familiar with Spring Web Flow 1, there is a useful section detailing the major changes introduced in Web Flow 2. Having not used Spring Web Flow in over a year, I found the summary provided enough information to reacquaint myself.

Chapter 2 - Setup for Spring Web Flow 2

Chapter 2 details how to get Spring Web Flow setup in a Spring web application. Details on where to find the source code and examples provides a good starting point for users who wish to see Web Flow in action before delving into the details. An explanation of tooling support, such as setting up Eclipse to visualise flow, is a helpful addition especially with the prevalent screenshots.

Chapter 3 - The Basics of Spring Web Flow 2

As expected, this chapter covers the necessities for building a Web Flow, focussing on defining the flow using XML. This is by far the most important and useful chapter of the book. The chapter is just over 50 pages long, but is well worth the read as most sections are fundamental in using Web Flow, topics include: flow descriptors (including a diagram), flow scoped persistence, the newly supported EL expression language, scope levels, @Autowired behaviour gotchas, inputs & outputs, subflows and end states.

Chapter 4 - Spring Faces

Not being a JavaServer Faces (JSF) user, I skimmed over this chapter, however it is available as a sample chapter.

Chapter 5 - Mastering Spring Web Flow

This chapter contains a mix of topics. The first section includes further information on the usage of subflows, however I feel the explanation is a little brief.

The next section talks about integration with the Spring Javascript project. Spring Javascript is explained as being an abstraction layer on top of existing toolkits (only Dojo supported so far), but the example given has a hardwired dependency on dijit.form.DateTextBox. I’m not sure if this is just a bad example or if that is how Spring Javascript works. An introduction to the Tiles framework is then given and tied in nicely with an explanation of how to load page fragments using Spring Javascript.

The final section in this chapter covers advanced configuration of flows. I would advise using this section purely as a reference as it is heavy on detail.

Chapter 6 - Testing Spring Web Flow Applications

Being a bit of a testing zealot, this was the section I was really hanging out for. The opening sentence reads, “Testing is an important aspect in every software development process”. Off to a good start, unfortunately this chapter didn’t live up to my expectations.

The Web Flow specific test setup and assertions are explained well, for example calls such as context.setEventId(“login”), this.resumeFlow(context) and assertFlowExecutionEnded().

The example then introduces EasyMock to help isolate and focus the unit tests. However this example has a glaring issue; it creates a mock of the wrong object. The example models a user login using a UserService to fetch a user by username. You would expect the mocked object in this case to be the UserService, but the example mocks out the underlying EntityManager. As a result the unit test for the flow ends up setting expectations on Hibernate HQL, thus polluting the flow’s unit test with database queries that should really be tested at the service or DAO layer. If you change the way users were fetched in the DAO (or you moved away from Hibernate) you wouldn’t expect your Web Flow tests to be affected.

My advice when reading this chapter is to skip to the section titled More testing with EasyMock. This section shows correct usage of EasyMock and demonstrates a test driven approach to testing.

Chapter 7 - Security

The final chapter covers the integration of Spring Security, the only real option for security in Spring. The details in this section are largely not specific to Spring Webflow, however they are important for developing any non-trivial application and are well explained with examples.

Conclusion

I would recommend this book to any developer new to Spring Web Flow. The concepts and much of the implementation between Web Flow 1 and 2 remains the same, meaning this isn’t an essential read for existing Web Flow users.

Spring’s Dependency Injection & MVC

Below are slides from a presentation I gave to colleagues at Kiwiplan. The presentation covered two Spring Framework topics, the first being a brief introduction to Spring’s Dependency Injection Container. The second presentation was an introduction to Spring’s MVC (web) component, with a focus on the annotation style introduced in Spring 2.5. PDF versions are available for both Dependency Injection and MVC.

Unit Testing Fundamentals

Below and attached are slides from a presentation I gave to colleagues at Kiwiplan. The presentation covers a range of topics regarding unit testing best practices, including test driven development (TDD), mocking frameworks, avoiding over-specification and test coverage. The slides also include diagrams to help explain the concept of isolating code through the use of seams.

I’ve attached the final outcome of the live TDD examples. Obviously TDD doesn’t come across very well as a final solution, however the code also provides basic examples of the Mockito and Rhino Mocks libraries. The code style is based on Spring Framework’s annotation driven MVC framework.

Java example code - JUnit, Mockito, EclEMMA (Eclipse Java coverage) VB.Net example code - NUnit, Rhino Mocks

Using Dojo

Below are slides from a presentation I gave to colleagues at Kiwiplan. The slides cover how to use some core Dojo APIs and also showcase some of the features Dojo provides.

I also modified the javascript console created for my previous blog entry to use Dojo. You can download the source to try out Dojo examples on your local box. You will need Java and Grails installed and can run the server using the usual grails command.

1
grails run-app

The console can then be accessed at http://localhost:8080/AjaxServer/ (only tested in Firefox).

Javascript & Ajax Basics (Slides + Console)

The following slides are from a presentation I gave at Kiwiplan (my employer).

I’ve also created a live Javascript console to play around with Javascript in a browser. You can download the source and play about with it on your local server. You will need Java and Grails installed and can run the server using the usual grails command.

1
grails run-app

The console can then be accessed at http://localhost:8080/AjaxServer/ (only tested in Firefox).

Thanks @cgarethc (development manager @ Kiwiplan) for allowing me to post this on my personal blog.

The Making of Rockin’ Robin

This post details the making of Rockin’ Robin, a client side mashup between last.fm and twitter.  If you missed my introduction to Rockin’ Robin, you can read the post here. Or you can try it out @ http://robin.rapaul.com/ (no longer running)

Querying

What makes this mashup special is that the entire mashup runs client side, all requests to the last.fm and twitter services are made in the user’s browser.  Being a purely in-browser mashup there are some restrictions as to what requests can be made, specifically current browsers do not support cross-site requests for regular XmlHttpRequests (XHR).  While this is a proposed feature for upcoming browsers, we need a solution that works with current browsers.

Enter dojo.io.script.get(), Dojo’s workaround for cross-domain requests.  The general gist of this hack is that it adds a script block to the page with the src attribute set to the query URL, the server then returns the JSON data as the content of the script block, this technique is known as JSONP.  Fortunately Dojo hides the complexity of this hack behind a similar interface to the regular request (dojo.xhrGet()).

Last.fm

Accessing last.fm’s API requires a registration key, which can bet set up on http://www.last.fm/api This page also details all the available API methods broken down into areas.  For the Rockin’ Robin mashup we are concerned with finding the most recently scrobbled tracks which are accessible via the user.getRecentTracks method.  Below is a code snippet for making the request to load the data from the last.fm API.

The data returned by this request includes that meta information for the last 5 tracks submitted to the user’s last.fm profile.  This information includes the artist, album (including cover art links), track name as well as when the track was played.  This information is used to build up the recent track HTML as shown below.

Twitter

The next step is to query twitter for tweets that contain the keyword artist and title combination.  Twitter’s API can be viewed at http://apiwiki.twitter.com/Search+API+Documentation.  No registration key is required, simply make a call to their public search API, e.g.  http://search.twitter.com/search.json?q=MGMT+Kids

It is now simply a matter of extracting the required data to build the elements to add to the page.

Building the HTML

Dojo provides a handy method for setting attributes on nodes (attr), the API was designed for existing nodes, however it can be used by passing in a newly created node. Here we use dojo.query to return a nodelist which gives access to the attr function then returns the first item (the node we just created).

I’ve heard from @amatix that a Builder equivalent is slated for a post 1.2 release of Dojo which will hopefully do away with the above build function and make element creation tasks simpler.

Bookmarking Support

To allow users to bookmark and link to their Rockin’ Robin page, the username is stored in the URL hash. This is a two stage process, the first is to append the username to the URL, e.g. http://robin.rapaul.com/#GexNZ The below snippet strips off any existing hash and adds ‘#username’ to URL.

The username also needs to be extacted from the URL when the page is first loaded.  The username is then used to populate the username text box and kick off the mashup.

That wraps up the major technical details of Rockin’ Robin, you can browse the full source on github.

Rockin’ Robin

Introducing Rockin’ Robin (no longer running), a mashup between Last.fm and Twitter.  Head over to http://robin.rapaul.com/ to check it out if you haven’t already.

The basic premise is that you enter your Last.fm username, Rockin’ Robin fetches your recently scrobbled tracks, then mashes them up with the latest tweets from Twitter. It’s an excellent way to see what the Twitter community thinks of your tracks and to find Twitter users who have similar musical tastes. Of course you don’t need to enter your own username, you can enter the username of any Last.fm user to mashup their latest tracks.

Below is a screenshot (click to enlarge) highlighting some of the mashup goodness. Electric Feel by MGMT is the recently played track, with tweets shown from different Twitter users. To view more details on the artist, track or Twitter user you can click through to Last.fm or Twitter using the links (orange text).

Rockin’ Robin is in its early stages of development, as such there are many things that should/could be done to make Rockin’ Robin more rockin’.

Some ideas include:

  • Allow Twitter users to add there own tweets to the conversation from within Rockin’ Robin.
  • Show more tweets for popular tracks.
  • Tweak the Twitter API search to favour real user comments over radio station type tweets.
  • Show shortcut links to your Last.fm friends to make mashing up their recent tracks a simple click away.

If you have any suggestions or comments please feel free to add them below.

Also stay tuned for a follow up post “The making of Rockin’ Robin” which will cover the technical side including: Accessing Twitter & Last.fm APIs, JSONP and Dojo Toolkit (query, behavior, script.io).