You are currently browsing the category archive for the ‘Java’ category.

In my previous post I included some code to get the currently logged-in user. This code was copy-and-pasted from the sample applications provided in the SDK. Let’s consider this previous code to be a prototype. Real software development should always be test-driven, otherwise it’s just an exercise in building legacy code.

I’ve heard good things about two Scala based testing frameworks: ScalaTest and Specs. After some investigation into both I’ve decided to run with Specs. I intend to test in a behavioural manner and so don’t need the flexibility of other testing styles that ScalaTest provides. In my opinion Specs facilitates a cleaner testing style and has really wonderful integration with my preferred mocking library, Mockito. In the end it’s really just a matter of personal preference.

The static call

My first challenge to overcome is the static method call to the Google App Engine’s UserServiceFactory:


As it stands, the LoginSnippet object is untestable without including a mocking framework that supports the mocking of static method calls. Whilst Mockito provides simple and elegant mocking, it does not support the mocking of static method calls.

A quick introspection into the UserServiceFactory shows that (as of v1.2.0) the factory method is simply:

return new UserServiceImpl();

But it would be a bad idea to replace the current call to the factory with this instantiation because:

  1. it may not be backwards compatible as the GAE SDK is updated;
  2. it may not be the same implementation once deployed to the service; and
  3. it simply doesn’t work (UserServiceImpl is package private).

At this stage I’m forced to modify my class to facilitate my test. The primary constructor is modified to take an injected UserService. (It makes me cringe a bit to do this, but can it be done without using AOP or a different mocking library? Please fill me in on the secret if you know how).

 1: class LoginSnippet(userService: UserService) {
 2:     def this() = this (UserServiceFactory.getUserService)
 3:     def render(request: _root_.javax.servlet.http.HttpServletRequest) = {
            ... function continues as per my previous post ...
14:     }
15: }

The class definition on line 1 provides a new primary constructor. It now takes a UserService parameter. On line 2 a zero-arg constructor is defined that delegates to the primary constructor. There’s nothing particular to Scala in this scenario. However, it is worth noting that the execution of UserServiceFactory.getUserService now occurs in the constructor. If I needed it to continue to be executed in the render function I could do the following:

 1: class LoginSnippet(getUserService: => UserService) {
 2:     def this() = this ({UserServiceFactory.getUserService})
 3:     def render(request: _root_.javax.servlet.http.HttpServletRequest) = {
 4:         val userService = getUserService

The distinction here is that the constructor now takes a parameter which implies (=>) a UserService. It may be a literal UserService instance (as our test-time mock would be), or it may be a code block that returns a UserService, as can be seen on line 2 (note the added curly braces). If a code block is passed, it will not be executed until invoked on line 4.

Running Specs with Mockito via Ant

As is stands, there is currently a small trick to getting Specs running via Ant. It is clearly documented on their site, but I sometimes have a blind spot when it comes to RTFM’ing. Here it is in a nutshell:

1: import org.specs.Specification
2: import org.specs.mock.Mockito
3: import org.specs.runner.JUnit4
4: class SnippetSpecs extends JUnit4(snippetSpec)
5: object snippetSpec extends Specification with Mockito { ... }

The Specifications must be defined in an object (line 5), but the JUnit Ant task will require a class instance (line 4). The class must be something that JUnit knows how to run and so must extend the Specs JUnit4 runner. Finally, the addition of the Mockito trait (line 5) provides syntactic sugar to sweeten the mocking experience.

In the Ant build.xml the specs are executed with the junit task. The batchtest fileset should include the classes (in my case *Specs) and not the objects (*Spec).

Testing the sign-in snippet with mocks and XML matchers

The sign-in snippet should be shown when we don’t have a currently logged-in user. This forms the basis of my first specification. The task seems simple – ensure the user is null and assert the correct XHTML is returned.

1:  "LoginSnippet with an unknown user" should {
2:      "Provide a login prompt" in {
3:          userService.getCurrentUser returns null
4:          request.getRequestURI returns "requestURI"
5:          userService.createLoginURL("requestURI") returns "loginURL"
6:          val xhtml = snippet render request
7:          xhtml must ==/(<p>Hello! <a href="loginURL">Sign in</a> just for kicks.</p>)

The specification is described on lines 1-2. The mock expectations are established on lines 3-5 (notice how clean the syntax is, thanks to the Specs’ Mockito trait?). The code under test is executed on line 6. The expectation is asserted on line 7.

The expectation makes use of one of Spec’s XML matchers. Matchers are powerful tools for asserting only the aspects of the comparisons that are relevant. In this case, the must ==/ matcher compares the equality of a node sequence whilst ignoring whitespace.

Testing the sign-out snippet – splitting hairs over Atoms

The sign-out snippet seems equally as straight-forward, but there is a catch. My first approach was:

1:  "LoginSnippet with a known user" should {
2:      "Provide a logout prompt" in {
3:          val user = new User("x", "y")
4:          userService.getCurrentUser returns user
5:          request.getRequestURI returns "requestURI"
6:          userService.createLogoutURL("requestURI") returns "logoutURL"
7:          val xhtml = snippet render request
8:          xhtml must ==/(<p>Hello, x! Now you can <a href="logoutURL">sign out</a> again.</p>)

This specification fails! The XML on line 8 seems to be what we are receiving, but the equality matcher failed. After inspecting the returned node sequence closely it seems that the string “Hello, x! Now you can ” is not a single text element, but a chain of text/atom/text. The Atom (the parent class of Text) corresponds to the inlined user name (“x”) and, I assume, indicates that the inlined characters may not be valid XML text, but instead PCDATA or Unparsed.

To make the specification pass, line 8 needed to be modified to:

8:          xhtml must ==/(<p>Hello, {"x"}! Now you can <a href="logoutURL">sign out</a> again.</p>)

Now that I have the behaviour-driven testing essentials under my belt, it’s all go to proceed on adding some features to my application.


Google App Engine recently added support for Java. As a beautiful side-effect of this, Scala is supported. Unfortunately the delicious Scala-based web framework Lift does not work there, due to sandbox constraints in GAE around thread creation and JDBC access. (Though there is hope that David Pollak will get core Lift working with GAE as early as mid April*).

I’ve just uploaded a hello world app that is written with a JSP delegating to Scala. (It’s not worth clicking through to, but it is here if you need proof). Here is what I needed to do, once I had signed up and downloaded the SDK.

First you need to create the right project structure. You can get it automagically if you are using the Eclipse plugin, but I find that particular IDE to be a choking hazard. Here’s the structure I created manually.

  • project_root
    • src
    • web
      • WEB-INF
        • classes
        • lib

The one-and-only page is the JSP war/index.jsp. It delegates to the Scala class.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="" %>
    <h1>Just a test</h1>
    <%= LoginSnippet.render(request) %>

The custom Scala object providing the XHTML snippet to display is defined in LoginSnippet.scala


object LoginSnippet {
    def render(request: _root_.javax.servlet.http.HttpServletRequest) = {
        val userService = UserServiceFactory.getUserService
        val user = userService.getCurrentUser

        if (user == null) {
            <p>Hello! <a href={userService.createLoginURL
                (request.getRequestURI)}>Sign in</a>
                just for kicks.</p>
        } else {
            <p>Hello, {user.getNickname}! Now you can
                <a href={userService.createLogoutURL(
                request.getRequestURI)}>sign out</a> again.</p>

Scala classes need to be compiled to web/WEB-INF/classes (just as Java classes would). When compiling the class I required the following on the classpath:

  • appengine-java-sdk/lib/shared/geronimo-servlet_2.5_spec-1.2.jar (for HttpServletRequest); and
  • appengine-java-sdk/lib/user/appengine-api-1.0-sdk-1.2.0.jar (for the User functionality)

Some jars need to be deployed with your application. This simply means placing them in web/WEB-INF/lib. The jars I required were:

  • scala-library.jar (for the scala -> java bridging objects you get when scala is compiled, and several classes from scala.xml._ which I have used implicitly by defining the inline XML in the render function).
  • appengine-api-1.0-sdk-1.2.0.jar (which surprises me a little, as I thought GAE could provide this itself)

This is a reworked version of login as seen in the SDK’s demo application GuestBook. It is worth noting that the User functionality allows any username when running under the SDK’s development server, but integrates with Google account authentication once published to GAE.

Update: David Pollak – In case you missed it, Lift *does* run on the Google App Engine

Being an IntelliJ IDEA user for about 5 years now I have resisted the lure of the free open-source IDEs Eclipse and Netbeans. I tried being an early-adopter of Eclipse but found it significantly lacking in support for shortcut keys, refactorings or even a cohesive Java project view that made any sense. The ease in which it led to corrupted projects, and the propensity of buggy plug-ins was also disappointing. That was around 2004. I imagine it’s significantly improved now otherwise it would not have the overwhelming support it enjoys.

Around the same time I tried adopting NetBeans. This was in the day when you needed to mount the filesystem before you could start or open a project. Such strange design turned me off right away. The modern NetBeans is much nicer though and I have been following its progress since 5.0, when the inclusion of the Matisse GUI designer intrigued me.

This week I attended Sun’s EJB3 Business Component Developer course. We used NetBeans 5.5 and deployed our applications to the Sun App Server. The integration between the IDE and the server is sufficiently coupled to provide a modicum of productivity (although Parkes and Weeksy pointed out over a parma that it could be better). It was disappointing though that an IDE of NetBean’s age didn’t demonstrate maturity in regard to refactoring and context highlighting. I’ve just installed the NetBeans preview R6M10 and I can happily report that its “intelli-sense” (apologies for the commoditisation of this proprietary term) has improved. The reason for this, according to the latest NetBeans Magazine, lies in recent enhancements to javac.

Java SE 6 … introduced JSR 199 (Java Compiler API) and JSR 269 (Pluggable Annotation Processing API). The Java Compiler API enables tight and efficient integration with javac (and other Java source compilers), and JSR 269 … provides a source-level equivalent of reflection metadata. Working together, these new APIs allow IDEs and other tools to dig deeply into the structural information that javac extracts from source code.

The end result is that NetBeans is significantly improved. I now feel up to half as productive as I do when using IDEA, and that’s no mean feat! The magazine articulates many new features, including AST-based selection, semantic highlighting, improved code completion, vastly improved refactorings (they’d have to be), editable diffs, javadoc hints and more. Most, if not all, of these features have been present in IDEA for a long time, but it’s good to see NetBeans playing catchup. After all, there is an infinite price differential between the two product licenses. The closer NetBeans’ feature-set gets to matching that of the commercial product the better off the Java development world will be.