I’m playing around with some web frameworks lately and to see what’s in store with Spring 3 MVC (never did too much with it) I gave it a try to see how it handles Ajax. According to ajax simplification announcement it should be possible to get up and running in (almost) no time.
We will do a simple web application which will show the current time via Ajax.
The directory layout (using maven) should look like this:

Directory Layout
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Spring3MVC</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>spring</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> </web-app>
The web.xml holds no secrets. The Dispatcher servlet is defined and it should react on everything *.html.
Since we named our Servlet ’spring’ we need to add a servlet configuration for that. It goes in WEB-INF as well.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.maxheapsize.springmvc3.controller" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
It uses the component scanning feature of spring and instructs spring to check the package ‘com.maxheapsize.springmvc3.controller’ for controllers. Furthermore a url based view resolver is defined which uses Jstl and looks into /WEB-INF/jsp for jsp with the ending ‘.jsp’.
In WEB-INF/jsp/hello.jsp we define a jQuery snippet for the Ajax request and provide a button which we should push if we want to know the time.
<jsp:useBean id="message" scope="request" type="java.lang.String"/>
<html>
<head>
<title>Spring MVC Ajax Demo</title>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript">
function doAjax() {
$.ajax({
url: 'time.html',
data: ({name : "me"}),
success: function(data) {
$('#time').html(data);
}
});
}
</script>
</head>
<body>
${message}
<button id="demo" onclick="doAjax()" title="Button">Get the time!</button>
<div id="time">
</div>
</body>
</html>
How does Spring now know which classes or methods to call? Here comes the nice part about it.
package com.maxheapsize.springmvc3.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.Date;
@Controller
public class HelloWorldController {
@RequestMapping("/hello")
public ModelAndView helloWorld() {
return new ModelAndView("hello", "message", "Spring MVC Demo");
}
@RequestMapping(value = "/time", method = RequestMethod.GET)
public @ResponseBody String getTime(@RequestParam String name) {
String result = "Time for " + name + " is " + new Date().toString();
return result;
}
}
The RequestMappings define the Url’s which can be called to reach that code. So the helloWorld method is available with ‘hello.html’ in the web app. Why hello.html and not just hello ? Because we said so in the web.xml. I included a sample message which will be shown at the web page when this method is called.
If you now push the button on the webpage, ‘time.html’ with a parameter ‘name’ is called. This will go directly to the second method. Spring will also check if a string parameter ‘name’ (@RequestParam) is present in the original request. The @ResponseBody annotation indicates that a method return value should be bound to the web response body.
The result will be returned and shown in the webpage.

Ajax Result
Overall this is a pretty nice integration. I tend to use Spring for many projects and this makes it even easier to write some nice web apps in it. If you have a single page application and all you do is sending ajax request back and forth this might be a solution.
JSON response Update
To get a JSON response from your Controller you need to:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.5.3</version>
</dependency>
in their pom.xml.
@RequestMapping(value = "/demo", method= RequestMethod.GET) public @ResponseBody MySimpleDataObject doSomething(@RequestParam name, @RequestParam email)
jQuery.getJSON("demo.html", {name: name, email: email}, function (data) {
alert(data.someValueInMySimpleDataObject);
});
See also Ralf’s post about Json and Spring MVC.
I use Apache Trinidad at work and since JSF 2 is now final I decided to play with it a bit.
Of course this is going to be the classic Hello World example (as there are many other like this around the web).
First you need to setup a simple Maven project.
The file layout should be something like that.

Directory Layout for JSF 2 Ajax Demo
After that change your pom.xml to include the servlet and jsf2 libs.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.maxheapsize</groupId>
<artifactId>jsf2demo</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>jsf2demo Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.0.0-b13</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.0.0-b13</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
<build>
<finalName>jsf2demo</finalName>
</build>
<repositories>
<repository>
<id>maven2-repository.dev.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2</url>
</repository>
</repositories>
</project>
First we are going to create the managed bean to hold the name we are going to enter.
package com.maxheapsize.jsf2demo;
import javax.faces.bean.*;
import java.io.Serializable;
@ManagedBean
@SessionScoped
public class HelloWorldBean implements Serializable {
private String name = "";
@ManagedProperty(value = "#{demoService}")
private Service service;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setService(Service service) {
this.service = service;
}
public String getReverseName() {
return service.reverse(name);
}
}
To demonstrate the dependency injection with JSF 2 I use a service to reverse the name. Simply add the @ManagedProperty with the name of the service and it will get injected. Of course we need the service. Here it is:
package com.maxheapsize.jsf2demo;
import javax.faces.bean.*;
@ManagedBean(name="demoService")
@ApplicationScoped
public class Service {
public String reverse(String name) {
return new StringBuffer(name).reverse().toString().toLowerCase();
}
}
Very simple…isn’t it ?
The only thing what’s missing is the web.xml and the webpage itself.
The web.xml is pretty straight forward and should not show any surprises.
<!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>
<display-name>Web Application</display-name>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
</web-app>
The index.xhtml has some differences from earlier versions of JSF. First, JSF now supports Ajax out of the box. To have this enabled you need to load the jsf.js javascript library. The inputText tag binds to our managed bean and includes an f:ajax tag. This tag determines which part should be rerendered (in this case the element with the id reverseName). F:ajax will execute on value holding components always with an ‘onchange’ event and on action components (like commandButtons) with an ‘onclick’ event.
The output will trigger the injected service in our managed bean and return the reversed input string.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>JSF Demo</title>
</h:head>
<h:body>
<h:outputScript name="jsf.js" library="javax.faces" target="body">
</h:outputScript>
<h1>Ajax JSF 2 Demo</h1>
<h:form>
<h:inputText id="name" value="#{helloWorldBean.name}">
<f:ajax render="reverseName"/>
</h:inputText>
<h:commandButton value="Say reverse Hi via Ajax">
<f:ajax execute="name" render="reverseName"/>
</h:commandButton>
<h:outputText id="reverseName" value="#{helloWorldBean.reverseName}"/>
</h:form>
</h:body>
</html>

JSF 2 Ajax Demo
And that’s it. Sure it’s a simple example, but so far I do like the minimal configuration and the ajax integration.
Here is a small update on my little fun project.
I released version 0.2 of quant. Now it will recognize all TestNG annotations which do not have a TestNG group (like @BeforeMethod, @BeforeClass etc.). The method ‘reportViolation’ on ClassTester will now report whats wrong with the examined class.
[/java]
assertFalse(classTester.isInvalidTestClass(),
classTester.reportViolation());
[java]
Above code will now report:
java.lang.AssertionError: Report for Class com.maxheapsize.quant.testclasses.SetupMethodWithoutTestGroup Ignore abstract classes: true Specified TestGroups : + testUnitTest * Methods with wrong test group: - testSetUp
In this way you know what went wrong and where to look for it.
Quant is now also available in my repository. To include it add the following code to your pom.xml.
<dependency>
<groupId>com.maxheapsize</groupId>
<artifactId>quant</artifactId>
<version>0.2</version>
</dependency>
For now you need to add my mvn repository to your pom. I’m about to have it mirrored to the official servers.
Have fun.
Did you ever wondered if all tests your team wrote are really running ? How many disabled tests does your code base have? How many public void methods do not have a @Test annotation (or at the class) ?
I saw all of that in the last years.
To overcome this situation I wrote a couple of java classes which will scan your java test sources and will examine the annotations (for TestNG, sorry JUnit). The code will detect if all public void methods do have a @Test annotation (either direct on the method or on the class) or if there are disabled tests. Both signals are most likely a sign of rotten code.
If you have different test groups defined like ‘unitTest’ or ‘integrationTest’ you want to make sure all tests are in at least one test group. This ensures if you run all test groups all tests are executed.
The usage is really simple. To make sure all your tests are ok is to write just another test which will check all tests.
ClassFinder classFinder =
new ClassFinder.Builder(sourceDirectory).build();
for (Class klass : classFinder.getClassList()) {
TestClassTester testClassTester =
new TestNGTestClassTester.Builder(klass).build();
Assert.assertTrue(testClassTester.allTestMethodsHaveValidTestGroup());
}
You need to specify the source files of your code so that all java files can be scanned. It is possible to exclude certain packages to be checked (via TestNGTestClassTester.Builder(klass).addExcludedPackage("testclasses").build()). After gathering all class names from the sources the code will check for @Test annotations in the test classes. You can also specify the test groups which all test should belong to (via addTestGroup("unitTest") in the builder).
Finding disabled test methods is very simple too (one of the unit tests)
@Test
public void testNoDisabledTest() {
DisabledTestFinder unitUnderTest =
new TestNGDisabledTestFinder.Builder(TwoTestGroups.class).build();
assertFalse(unitUnderTest.hasDisabledTests());
}
This would test a single class (but you can of course feed it with the results of the ClassFinder).
If you combine the possibility to break your build because of defect test classes and a continuous integration system, you can make sure everybody will annotate their classes correctly or never disables tests (or even better use a CI with delayed check in and personal build like Jetbrains Teamcity). Of course you can define your own thresholds for e.g. 30 disabled tests are allowed (I know sometimes you just can’t avoid it).
The code depends on testng and commons-io and is released under the Apache v2 license.
I still need to figure out where to put the maven2 sources. Either Google code or GitHub ? Any ideas?
Update: Code is available at Google Code Hosting.
Things to implement:
Jetbrains released a Google App Engine plugin for their IntelliJ IDE. I did not see any announcement about this at all.

New project inside IntelliJ for Google App Engine
You will have a new option when creating a new project. After supplying the path to the local app engine SDK your almost good to go. I needed to add the app engine jars as libraries to my project. That being out of the way you can start coding, run you local server (a pre configured run configuration is supplied) and also deploy it to Google all from within IntelliJ. I tested it with a very basic example with local development and remote deployment and this works really nice.
Thanks Jetbrains.
From the release notes:
This plugin provides the following features:
At Campfire One Google announced their App Engine for Java (this was in the rumor mill for a couple of days already). The first 10,000 developers would get an early look at App Engine’s Java language support. I would have almost missed it. Some tweets reminded me of registering with Google. I heard of AppEngine before but the fact that it was only available for Python did not make it very attractive to me. Now the game changed a bit with introducing Java (and other JVM languages (JRuby, partial Scala …), well Groovy for sure, Ola Bini has more on that).
After registering with my Google ID they wanted to verify my account with a sms text message. Google is just listing 3 countries and then ‘Other’ for sms verification and I expected it would not work with a german cellphone. But it did
.
The Tutorials on their site are working nicely (even if you don’t have Eclipse which they are always referring to). Just follow the instructions step by step, use ant and the command line to get through the examples. Don’t copy the template project, this is not in line with the documentation.
In the last hour or so I went from nothing to a running Guestbook App at Google (try it!). Once you get the environment right, the code is pretty straight forward.
I see a couple of things which I do like about the App Engine.
Support for Google Id and Sign In
AppEngine support sign in with an Google ID with 2! lines of code. Great. I don’t want to worry about that (this generates the Google login page and redirects).
UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser();
Automagic Persistence
With simple annotation you persist your objects. No mapping, no nothing. You can configure if you want to be using JDO or JPA. No database hassle or whatsoever. Of course it needs to be seen how this work with more complex domain models.
@PersistenceCapable(identityType = IdentityType.APPLICATION)
..
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;
@Persistent
private User author;
@Persistent
private String content;
@Persistent
private Date date;
...
Local Development – Remote Depolyment
Everything works locally. If you deploy it to Google it uses the Google facilities. I don’t have to worry (deployment is one ant command).
Scalability and free Use
If your application is successful you can grow with Google. More Resources at your fingertips. Of course this costs money (but you should make money at this point right?). If you are beyond the free 10 GB bandwidth in/day, 10 GB bandwidth out/day, 5 million pageviews a month, 46.3 cpu h/day and 1000 emails/day you pay:
Monitoring
You get nice and detailed overview of the status of you application. You can upload new version any time and go live on demand.

Google AppEngine Dashboard
This this is limited access and Google titles it ‘early look’ there must be some gotchas but I hope they will get worked out. Of course you will depend on Google’s code but I could imagine with a good abstraction layer you can minimize the dependencies to the AppEngine (although replacing some services you might need to use could be hard).
The downside of using it are (gathered from various sources)
For sure there are some more benefits in hosting with Google (I guess the same goes for Amazon with S3/EC2). In the past I heard from a couple of startups using those kind of services but I never imagined that it would be that easy. As I said, I was up and running in under one hour.
I certainly will use AppEngine for a small application in the near future.
A couple of days ago I had the case that I needed to test a method with different parameters. I ended up writing a couple of test methods differing only in passing various arguments to the unit under test.
Tonight I was at a TestNG talk and while I knew most of the stuff already the DataProviders (which I heard of before but unfortunately never really payed attention to) really caught me.
Now I can create a DataProvider which generates test data. Each of these data sets will result in call of the test method with the corresponding arguments.
The following code will test a String to Property Converter if it works correctly. It takes two parameters, first the string to be converted, second the result which I will assert.
@Test(dataProvider = "convertTestDataProvider")
public void testConvert(String property, String result)
{
Properties properties =
stringPropertyConverter.convertString(property);
Assert.assertTrue(properties.get("A").equals(result));
}
Now the DataProvider must return an array of array of objects. TestNG will cast the return values to the method signature of all the tests with the corresponding annotation.
@DataProvider(name = "convertTestDataProvider")
public Object[][] convertTestDataProvider()
{
return new Object[][]{
{"A=", ""},
{"A=1", "1"},
{"A=2=3", "2=3"},
{"A=2" + StringPropertyConverter.ideaLineSeperator +
"# Comment" +
StringPropertyConverter.ideaLineSeperator + "C=1", "2"},
};
}
Here I cover 4 test cases. It is very easy to add more tests just by adding one more line with the values to test and the expected result.

TestNG results with DataProvider
This will save me some amount of time.
Good Job Cedrik & friends.
Next step: How to make sure you cover all the relevant test cases (and having a systematic way of getting there). Anybody has an Idea?
You use Spring in your application everywhere. You love it. Everything gets injected and is configured by Spring. Great. Why not use the same technology to wire up your tests?
The bottom line is: Starting the Spring Context all the time in your tests drags you down at the costs of development time.
Here is why:
1. Turnaround times are much faster
When you discover a bug which might have not been covered by tests yet (this happens to me all the time) you are much faster rerunning your tests without the application context. In the application I’m working on it takes about 20-25 seconds to run a test with application context, whereas a pure unit test just takes 1 second. Now imagine this: changing some code and rerunning tests like 100 times saves you a lot of time. The tests run faster, you don’t get distracted because you could do something else in those 20-25 seconds, like browsing some web pages (you want to be efficient and use the ’spare’ time to read up the newest stories on infoq.com). But then you need to switch windows, read something, switch back, wonder what you did, rethink the problem and so on. In the end it costs you much more time than it seems.
2. Enables you pratice Test Driven Development
Since you can run test faster without the Spring context, you can start doing Test Driven Development. Before any line of production code gets typed into your IDE, write the test. That the code does not compile is the first test, go fix it by writing the actual stub for the class which you want to test. Now onto the next test. It fails, you implement the feature and rerun the test. This goes on and on and on until you fully implemented the requirements. It forces you only to implements the things needed and not more.
Uncle Bob’s three rules of Test Driven Development
1. You are not allowed to write any production code unless it is to make a failing unit test pass.
2. You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.
3. You are not allowed to write any more production code than is sufficient to pass the one failing unit test.
Learn more about Test Driven Development with Uncle Bob.
Without fast unit tests you just can’t do TDD.
3. No corrupt test configuration
Depending on the setup of the project you might have an extra Spring application context configuration for tests. You have to configure and keep it up to date. Things can go wrong here and will be detected very late.
If you use the application context in tests you get the beans injected but sometimes you need to mock them, because you depend on an application server, a database or an external service which you don’t want to start up every time you run tests. You must be very careful with that. Using mocks with Spring application context can be very powerful but also very dangerous. You have to make sure that you remove the mocks after you are done with your tests (and reinject the right ones) or mark the methods which are injecting mocks with the DirtiesContext annotation so Spring can reload them. I did debug forgotten DirtiesContext annotations one too many times. The mock object lives on in your context and 282 test later an exception occurs for no reason and you start debugging at a wrong place.
You will not discover those mock problems until you run the full suite of tests. Since your tests are slow you not very likely to run all the on a regular basis to see if everything plays well together. No, you run all tests right before checkin and then start to wonder why some tests somewhere fail. Depending on the size of the changes and the project it will require some substantial amount of time to find and fix the problem.
You might say: “But I need my application context in the tests. My Service which I want to test has so many dependencies, I just can’t mock them all!”
While this happened to me as well it might turn out that this service is maybe doing too much. Split the functionality into smaller packages and test them individually (that’s the S in SOLID principles). The danger in testing a complex service with mocks only is also that you might end up mocking everything and you don’t do any real tests anymore (happened to me, I threw hours of coding away).
There is one reason to run tests with a Spring application context. It’s just not in unit tests. If you want to test the integration with external services (like databases or webservices) you need to use it of course. Just make sure you really just test the interaction between your service and the external interface and not more (but even that is debatable in some cases). That’s what I call an integration test.
Do you use Spring in your unit tests? What experiences did you make?
I do work with language property files pretty much every day (since I’m the GUI guy in the team). The files are updated on different branches copied up to the trunk and merged down to new branches, sometimes even updated by our product owner. We got a couple of times into not so funny merge conflicts since people did not sort the property files in the same way. To get around that we used an external tool to sort the files just before committing them.
Right, we can do better than this.
I wrote a small plugin for IntelliJ IDEA (and turns out my colleague too) for sorting these inside IDEA. I took the easy approach to sort them in the editor window. Simply open a properties file and choose Code – Sort Properties. It detects if this is a real properties file (e.g. all lines do have a # at the start or do follow the pattern key=value) and sorts them. If things go boom you always can undo
.
You can get it from here. It’s just 7KB since I did not include the testng jars.
Today I got an interesting ctrl+space code completion in IDEA 8.1. Easteregg anyone ?

Update: Seems like this is part of IDEA since at least release 4.0.