JSF, Iterating with tomahawk radio buttons, t:datalist, a4j:repeat

The standard JSF radio buttons h:selectOneRadio render a load of old school html (i.e. they use table tags to do layout, (all a bit 1996)).

e.g. JSF h:selectOneRadio tag

<h:selectOneRadio id="aRadio">
	<f:selectItems value="#{radioOptions.items}" />
</h:selectOneRadio>

Code for #{radioOptions}

import java.util.ArrayList;
import java.util.List;

import javax.faces.model.SelectItem;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

@Name("radioOptions")
@Scope(ScopeType.APPLICATION)
public class RadioOptions
{
	public List<SelectItem> items = new ArrayList<SelectItem>();

	public RadioOptions()
	{
		items.add(new SelectItem("1", "label 1"));
		items.add(new SelectItem("2", "label 2"));
		items.add(new SelectItem("3", "label 3"));
	}

	public List<SelectItem> getItems()
	{
		return items;
	}

	public void setItems(List<SelectItem> items)
	{
		this.items = items;
	}
}

Note: I’m using jboss seam in the example above, but you could easily remove the seam annotations and define the bean in using jsf managed beans or faces config etc. Also the examples here are a bit mickey mouse and could be better.

Under JSF 1.2 will be rendered as

<table id="myForm:aRadio">
	<tr>
		<td>
			<input type="radio" name="myForm:aRadio" id="myForm:aRadio:0" value="1" />
			<label for="myForm:aRadio:0">Label 1</label>
		</td>
		<td>
			<input type="radio" name="myForm:aRadio" id="myForm:aRadio:1" value="2" />
			<label for="myForm:aRadio:1">Label 2</label>
		</td>
		<td>
			<input type="radio" name="myForm:aRadio" id="myForm:aRadio:2" value="3" />
			<label for="myForm:aRadio:2">Label 3</label>
		</td>
	</tr>
</table>

Anyway this limitation is well known and as a result we’ve been using the apache tomahawk t:selectOneRadio (using the layout=”spread” attribute) and t:radio tags to provide more flexible layouts which can be styled by css.

Iterating through a list of select items

There are times when I want to render the radio buttons in a flexible fashion (offered by t:radio) using a loop tag such as t:dataList or a4j:repeat e.g.

<!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:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:fn="http://java.sun.com/jsp/jstl/functions" xmlns:c="http://java.sun.com/jstl/core" xmlns:t="http://myfaces.apache.org/tomahawk" xmlns:a4j="https://ajax4jsf.dev.java.net/ajax">
<f:view>
<h:form id="myForm">
	<!-- radio button, layout spread  -->
	<t:selectOneRadio id="myRadio" forceId="true" layout="spread">
		<f:selectItems value="#{radioOptions.items}" />
	</t:selectOneRadio>

	<!-- data list, loops through all the radio button options -->
	<t:dataList var="helper" value="#{radioOptions.items}" rowIndexVar="idx">
		<!-- example html, not constrained to table layout -->
		<h1>Heading</h1>
		<t:radio for="myRadio" index="#{idx}"/>
		<h1>Another Heading</h1>
	</t:dataList>
</h:form>
</f:view>
</html>

Unfortunately this doesn’t work and throws:

java.lang.IllegalStateException: Could not find component 'myRadio' (calling findComponent on component 'myForm:j_id3:0:j_id5')

The Fix:

I almost always forget this which is why im blogging about it,

<t:radio for="myRadio" index="#{idx}"/>

needs to be replaced with

<t:radio for=":myForm:myRadio" index="#{idx}"/>

The tomahawk t:radio component must have the fully qualified component name of the t:selectOneRadio name otherwise it cannot find it.

Since the form is defined as:

<h:form id="myForm">

:myForm needs to be prefixed to the for attribute of the t:radio giving :myForm:myRadio

I take absolutely no credit for this because its explained here and on the Myfaces wiki this article is merely a note to self.

Btw, the above works with a4j:repeat as well as t:datalist

Currently tomahawk isn’t working in JSF 2.0 which is a shame as we are looking to upgrade very soon. Hopefully a decent radio button will become part of JSF 2 at some point.

Update: Fully Qualified JSF Name

A bit of searching around on the web took me to Lincoln Baxter’s blog where he mentions rendering components outside of the form and explains that the first “:” tells JSF to start looking from the very top of the JSF View Root. Thanks for that!

Maven site generation error: DTDDVFactoryImpl does not extend from DTDDVFactory

When generating a site with Maven, we encountered the following exception when a particular reporting plugin was executed:

org.apache.xerces.impl.dv.DVFactoryException:
DTD factory class org.apache.xerces.impl.dv.dtd.DTDDVFactoryImpl does not extend from DTDDVFactory.

This basically meant that an incompatible version of xerces was trying to be run. We have everything set to use Java 1.6, which ships with its own version of xerces. After some debugging, it was tracked down to the maven-site-plugin which we had recently upgraded to use version 2.1 of the plugin by specifying it in our pom file like so:

<pluginManagement>
	<plugins>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-site-plugin</artifactId>
			<version>2.1</version>
		</plugin>
	</plugins>
</pluginManagement>

The maven-site-site plugin has the following dependency structure:

  • org.apache.maven.plugins:maven-site-plugin:maven-plugin:2.1
    • org.apache.maven.doxia:doxia-module-xhtml:jar:1.1.2 (compile)
      • org.apache.maven.doxia:doxia-core:jar:1.1.2 (compile)
        • xerces:xercesImpl:jar:2.8.1 (compile)

It is the dependency of the xercesImpl jar 2.8.1 that is the problem. To get around this issue, you can tell the maven-site-plugin to exclude a particular dependency. This can be done like so:

<pluginManagement>
	<plugins>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-site-plugin</artifactId>
			<version>2.1</version>
			<dependencies>
				<dependency>
					<groupId>org.apache.maven.doxia</groupId>
					<artifactId>doxia-core</artifactId>
					<version>1.1.2</version>
					<exclusions>
						<exclusion>
							<groupId>xerces</groupId>
							<artifactId>xercesImpl</artifactId>
						</exclusion>
					</exclusions>
				</dependency>
			</dependencies>
		</plugin>
	</plugins>
</pluginManagement>

There are a couple of maven reporting plugins that we found produced this exception when run with maven-site-plugin 2.1. These plugins are:

If you use an older version of the maven-site-plugin then the above mentioned reporting plugins should work ok. It is only when specifying a version of 2.1 or above that the exception occurs.

Some of the solutions suggested on the net didn’t work for us, like adding the xercesImpl jar as a dependency to the actual reporting plugin in question, so hopefully the solution mentioned in this post is helpful.

3D Secure and the PaReq field in Google Chrome & Safari Browsers

I recently had to implement the 3D Secure payment system.

In order to do this 3 fields must be sent to the 3D Secure ACS (Access Control Server)

  • MD
  • Term Url
  • PaReq (Payer authentication request)

Initally everything went well until we tested our pages in Google Chrome and Safari. Under both browsers the 3D Secure inline frame displayed the following message

“Error decoding PAREQ message”

A support page mentions that a PaReq contains newlines and that if any of these are missing the PaReq decoding will fail. The page also mentions that there are issues with Chrome and Safari but provides no solution.

So what is the problem?

The problem is indeed the newline.

In our markup we use and EL (Expression Language) to output the PaReq e.g.

<input type="hidden" name="PaReq" value="#{paReq}" />

If the PaReq returned a string such as

"I am
The PaReq
"

Note the quotes above mark the begining and end of the string. The string itself is terminated by a newline, in code it would be:

String paReq = "I am\nThe PaReq\n";

The browser should generate the following markup

<input type="hidden" name="PaReq" value="I am
The PaReq
" />

However Chrome and Safari generate the following markup (as both browsers do this I assume its a Webkit thing)

<input type="hidden" name="PaReq" value="I am
The PaReq" />

Note, the traililng newline has disappeared and herein lies the problem, the server fails to recoginse the PaReq as the trailing newline has gone (currently Chrome 4.0.429.89 contains the above bug).

The fix? Dont use Chrome or Safari, Only kidding

The way we overcame this was to use a “hidden” textarea

<textarea name="PaReq" style="display:none">#{paReq}</textarea>

Which renders

<textarea name="PaReq" style="display:none">I am
The PaReq
</textarea>

In all browsers and preserves the trailing newline. The style=”display:none” hides the textarea. Although this is crude it does provide a fix for Chrome and Safari.

Suppress logging in java unit tests

Here are a couple of different ways of suppressing logging when running unit tests. If you are using apache commons logging then you can suppress logging with the following code:

LogFactory.getFactory().setAttribute(
                "org.apache.commons.logging.Log",
                "org.apache.commons.logging.impl.NoOpLog");

If running your unit tests with JUnit, it is probably best to put this code in the setUp() method. However, if you only wanted it suppressed on particular tests, it could go at the top of the test method instead. Bear in mind that if the logger is a static in the class you are testing, you  may need to then reset the attribute at the end of the test method, otherwise, any tests being run after that one will also have their logging suppressed.

If you run your unit tests within an IDE, you may want to see the logging, but not see the logging when you actually run the build of your project with something like Maven. Thankfully, there is a very simple answer to this if you are using Maven. The maven-surefire-plugin is responsible for running the tests and there is a configuration option which needs to be specified to redirect all the test output to file instead of to the console. This keeps your build reports much cleaner as you aren’t interested in seeing the logging messages. As a bonus, since all output is saved to file, exceptions will also be output to file, so whenever exceptions are thrown in the methods being tested, the stack trace wont show up in the build report.

The configuration option that needs specifying is <redirectTestOutputToFile> and this needs to be set to true, as shown below.

<plugin>
	<artifactId>maven-surefire-plugin</artifactId>
	<configuration>
		<redirectTestOutputToFile>true</redirectTestOutputToFile>
	</configuration>
</plugin>

Mocking Statics and java.lang.IllegalStateException: no last call on a mock available

If you use PowerMock to mock a static object e.g.

mockStatic(FacesContext.class)

and encounter the following error:

java.lang.IllegalStateException: no last call on a mock available
at org.easymock.EasyMock.getControlForLastCall(EasyMock.java:174)
at org.easymock.EasyMock.expect(EasyMock.java:156)

Check that you have prepared the Class for test using the @PrepareForTest annotation.

e.g.

@RunWith(PowerMockRunner.class)
@PrepareForTest(
{
	FacesContext.class
})
public class ....

An excellent article discussing mocking statics by one of the PowerMock developers can be found here: http://blog.jayway.com/2009/05/17/mocking-static-methods-in-java-system-classes/

Note that you also need to @PrepareForTest any classes where you are expecting a private method call with expectPrivate.  If you don’t, your test execution will try and go into the private method and actually run all the code. The @PrepareForTest annotation can either go at the method level as shown in the example below, or at the class level as shown in the example posted above.

@PrepareForTest(ClassUnderTest.class)
@Test
public void testNext() throws Exception
{
	String privateMethod = "isNextEnabled";
	ClassUnderTest partMock = createPartialMock(ClassUnderTest.class, privateMethod);
	expectPrivate(partMock, privateMethod).andReturn(true);
	replayAll();
	partMock.next();
	verifyAll();
}

Cobertura code coverage with Maven and PowerMock

If you use Powermock for unit testing with Maven and Cobertura for code coverage, you are likely to be affected by the following issue noted on the PowerMock issue tracker. If you did not have the maven-surefire-plugin forkmode configured to ‘pertest’, you would find that any tests annotated with @RunWith(PowerMockRunner.class) had zero percentage code coverage when you viewed the resulting code coverage report produced by the cobertura-maven-plugin. Whilst running with ‘pertest’ fixed the issue, it was very slow to run the Maven build compared against a forkmode of ‘once’.

In September 2009, Cobertura released version 1.9.3 and one of the changes mentioned was the following:

  • Support the case where multiple classloaders each load the Cobertura classes.

Seeing this, I decided to test if that would fix the issue. At present, the latest version of the cobertura-maven-plugin is 2.3 which runs with Cobertura 1.9.2. There are some snapshots in the codehaus snapshot repository which run with Cobertura 1.9.3.  However, I found that the snapshots were constantly changing, and each run of the Maven build downloaded the latest version and sometimes the latest version had issues. There is probably a way to stop this from happening but if you don’t want to use snapshots, there is a change you can make to the 2.3 version which will also fix the issue. The cobertura-maven-plugin-2.3.pom file needs to be edited. It can be found in your repository under the following directory: org/codehaus/mojo/cobertura-maven-plugin/2.3/

Find the dependencies section of the pom file and change the versions of Cobertura from 1.9.2 to 1.9.3. There are two instances that need changing:

<dependency>
	<groupId>net.sourceforge.cobertura</groupId>
	<artifactId>cobertura</artifactId>
	<version>1.9.3</version>
</dependency>
<dependency>
	<groupId>net.sourceforge.cobertura</groupId>
	<artifactId>cobertura-runtime</artifactId>
	<version>1.9.3</version>
	<type>pom</type>
</dependency>

With that change, you should find that you can safely remove the ‘pertest’ forkmode configuration since by default the surefire plugin will run with forkmode set to ‘once’, and your cobertura code coverage results should be reporting correctly.

UPDATE (26th April 2010):

There is actually a better way of doing this which doesn’t involve having to edit the pom file for the actual plugin.

In your pom file you will have defined the cobertura-maven-plugin in the reporting section. The reporting section does not allow to add dependencies to a plugin. However the build section does, and the plugins defined in the reporting section will also pick up those dependencies. Therefore, you can also define the cobertura-maven-plugin in the build section as a plugin. This will allow you to specify some dependencies, as shown below.

<build>
	<plugins>
		<plugin>
			<groupId>org.codehaus.mojo</groupId>
			<artifactId>cobertura-maven-plugin</artifactId>
			<version>2.3</version>
			<dependencies>
				<dependency>
					<groupId>net.sourceforge.cobertura</groupId>
					<artifactId>cobertura</artifactId>
					<version>1.9.4.1</version>
				</dependency>
				<dependency>
					<groupId>net.sourceforge.cobertura</groupId>
					<artifactId>cobertura-runtime</artifactId>
					<version>1.9.4.1</version>
					<type>pom</type>
				</dependency>
			</dependencies>
		</plugin>
    </plugins>
</build>

This will then use cobertura 1.9.4.1.  Any version above 1.9.2 should fix the issue, but 1.9.4.1 is currently the latest and supposedly a lot faster than previous versions.

UPDATE (11th May 2010):

Good news! There is now version 2.4 of the cobertura-maven-plugin. This uses 1.9.4.1 version of Cobertura, so none of the above is now necessary.

Chaining EasyMock’s expectation return values

Recently I discovered quite a handy feature of EasyMock’s IExpectationSetters andReturn method. You are able to chain the return values so that you can return different values each time that expectation is called.

It becomes useful if you consider the following method, where Voucher is an object that cannot be instantiated and needs to be mocked:

public class VoucherHelper
{
	public static boolean isVoucherExpired(Voucher voucher)
	{
		boolean expiredVoucher = true;
		Date expiryDate = voucher.getExpiryDate();
		if (expiryDate != null)
		{
			Date now = new Date();
			expiredVoucher = now.after(expiryDate);
		}
		return expiredVoucher;
	}
}

To test this method, there are 3 tests that need to be done.

  • expiryDate returning null
  • expiryDate returning an earlier date than the current date
  • expiryDate returning a later date than the current date

This can all be done in one expectation line by chaining the ‘andReturn’ of the expectation.

@Test
public final void testIsVoucherExpired()
{
	Voucher voucher = createMock(Voucher.class);
	Calendar expiredDate = Calendar.getInstance();
	// Make it expired by taking a year off
	expiredDate.set(Calendar.YEAR, expiredDate.get(Calendar.YEAR) - 1);

	Calendar notExpired = Calendar.getInstance();
	// Make it not expired by adding a year
	notExpired.set(Calendar.YEAR, notExpired.get(Calendar.YEAR) + 1);

	// Test with date returning null, then returning expired, then returning not expired
	expect(voucher.getExpiryDate())
		.andReturn(null)
		.andReturn(expiredDate.getTime())
		.andReturn(notExpired.getTime());
	replayAll();
	assertTrue(VoucherHelper.isVoucherExpired(voucher));
	assertTrue(VoucherHelper.isVoucherExpired(voucher));
	assertFalse(VoucherHelper.isVoucherExpired(voucher));
	verifyAll();
}

EasyMock also allows chaining on the times method and the andThrow method, and all can be used at the same time if you wanted.

expect(voucher.getExpiryDate())
	.andReturn(null).times(2)
	.andThrow(new RuntimeException())
	.andReturn(new Date()).times(3);