Thursday, January 22, 2009

Simplest way to override hashCode(), equals(Object) and toString()

We all know that these three methods belongs to java.lang.Object, the parent of all other Java classes, and they are intended to be overridden by subclasses wherever appropriate.

Both hashCode and equals(Object) should be overridden for entity objects that have a database identity and value objects that are used to pass parameters and return result, especially if they are used in a Set or a Map.

An often overlooked benefit of overriding these two methods for value objects is that it makes assertion and verification of invocation on mock objects much easier and more resilient to changes.

As for stateless objects, such as web actions, service objects, entity managers, repositories and data access objects, there is little to gain by overriding these methods.

With regards to toString, it would make our life debugging or reading log file a lot easier if it is overridden even though business may not mandate this.

In "Effective Java", Joshua Bloch provides the following guidance on when it is appropriate to override these methods:
  • Override equals(Object) unless:
    • Each instance of the class is inherently unique.
    • You don't care whether the class provides a "logical equality" test.
    • A superclass has already overridden equals, and the superclass behaviour is appropriate for this class.
    • The class is private or package-private, and you are certain that its equals method will never be invoked.
  • (Item 9) Always override hashCode when you override equals
  • (Item 10) Always override toString

But, why are we not overriding these methods as often as we should? I can think of the following reasons:
  • When we write a new class, our focus is on the implementation of the core responsibility of the class. Overriding these methods are often a result of after thoughts.
  • We can "cheat" in unit testing by substituting "logical equality" test with a "uniqueness" test, especially if the value object is immutable so that the class under test does not need to defensively copy an incoming value object to preserve invariants.
  • As there is a fair bit of code in overriding equals(Object), it requires unit testing the correctness of the overriding, which can be several times longer than the overriding method itself, depending on how thorough your tests are.
  • These methods are considered "affordable debt" in order to meet a project deadline.

Is there a way to override these methods with least effort?

Yes. We'll go through several ways of overriding these methods to find the simplest way.

DIY
When hand-crafting equals method, make sure you follow the high-quality equals method recipe from "Effective Java":
  1. Use the == operator to check if the argument is a reference to this object.
  2. Use the instanceof operator to check if the argument has the correct type.
  3. Cast the argument to the correct type.
  4. For each "significant" field in the class, check if that field of the argument matches the corresponding field of this object.
    • Avoid the possibility of a NullPointerException if some instance fields are nullable.
  5. When you are finished writing your equals method, ask yourself three questions: Is it symmetric? Is it transitive? Is it consistent?

Some additional suggestions:
  • If the superclass also overrides equals method, invoke super.equals(obj) as well, provided that the superclass's overriding method does not use a getClass test in place of the instanceof test.
  • Unit test symmetry, transitivity and consistency.

Pros
  • No third-party dependencies

Cons
  • Humans are error-prone, so it definitely requires unit-testing
  • Can be time-consuming
  • Requires "maintenance" when adding new instance fields
  • equals(Object and hashCode() can get out-of-sync when introducing new instance fields

Code generation by IDE
In IDEA, select "Code" -> "Generate..." and select "equals() and hashCode()".

In Eclipse, select "Source" -> "Generate equals() and hashCode()...".

Both IDEs let you choose whether to use instanceof test or not, and which instance fields are used in these methods.

Pros
  • No third-party dependencies

Cons
  • Requires re-generation when adding new instance fields
  • Unit testing may be needed if the generated code is significantly "enhanced by hand"
  • equals(Object and hashCode() can get out-of-sync when introducing new instance fields without regenerating the code

Typical Use of Apache Commons Lang's Builders
The "typical use" of EqualsBuilder, as documented, is as follows:

public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof MyClass == false) {
return false;
}
MyClass rhs = (MyClass) obj;
return new EqualsBuilder()
.appendSuper(super.equals(obj))
.append(field1, rhs.field1)
.append(field2, rhs.field2)
.append(field3, rhs.field3)
.isEquals();
}


Pros
  • Flexible

Cons
  • Lengthy
  • May require some degree of unit testing, usually the reflexive test, null test and type test.
  • Requires "maintenance" when adding new instance fields
  • equals(Object and hashCode() can get out-of-sync when introducing new instance fields
  • Third-party library dependency (this should not be an issue as Apache Commons Lang in ubiquitous...)

The Simplest Way to Override these methods
The possibly simplest way is to use the reflection-based methods of the Apache Commons Lang's Builders, as shown below:

@Override
public int hashCode()
{
return HashCodeBuilder.reflectionHashCode(this);
// or
// return HashCodeBuilder.reflectionHashCode(23, 13, this);
}

@Override
public boolean equals(Object obj)
{
return EqualsBuilder.reflectionEquals(this, obj);
// or, if transient fields are tested while some other fields should be excluded, and the reflection should be done
// up to a certain class (there are many overloading versions, so choose the right one)
// return EqualsBuilder.reflectionEquals(this, obj, true, Parent.class, new String[]{"excludedField1", "excludedField2"});
}

@Override
public String toString()
{
return ToStringBuilder.reflectionToString(this);
// or, if you'd like to choose a different style
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}


Pros:
  • No "maintenance" when adding new instance fields.
  • Won't accidentally make hashCode() and equals(Object) out-of-sync when introducing new instance fields
  • No need to write unit tests for these methods because they are too simple to break.

Cons:
  • The overhead of reflection. But you shouldn't avoid these methods simply because of the overhead:
    • Unless your class is used in big Collections and as key in big Maps, the overhead should be insignificant.
    • Don't prematurely optimize. Wait until you identify this is where the bottleneck is using a profiler before you try a different implementation. In that case, don't forget to add unit tests first.
  • Does not apply to entity objects directly. For these objects with a database identity, the equality test should be based only on database key, preferrably unique natural key.

So, if you think this is good, then why don't you put it in the code templates?

Embed in Code Templates

If you use IDEA, go to "Settings" -> "File Templates", select "Templates" tab and edit the content of "Class" to the following:

#if (${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

#parse("File Header.java")

public class ${NAME}
{

@SuppressWarnings("unused")
private static final Log log = LogFactory.getLog(${NAME}.class);

@Override
public int hashCode()
{
return HashCodeBuilder.reflectionHashCode(this);
}

@Override
public boolean equals(Object obj)
{
return EqualsBuilder.reflectionEquals(this, obj);
}

@Override
public String toString()
{
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}

}


If you use Eclipse, select "Preferences", under "Java" -> "Code Style" -> "Code Templates", expand "Code".

Edit "New Java files" to something like the following:

${filecomment}
${package_declaration}

import org.apache.commons.lang.builder.EqualsBuilder;

import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

${typecomment}
${type_declaration}


Then edit "Class body" and change to the following:


@SuppressWarnings("unused")
private static final Log log = LogFactory.getLog(${type_name}.class);

@Override
public int hashCode()
{
return HashCodeBuilder.reflectionHashCode(this);
}

@Override
public boolean equals(Object obj)
{
return EqualsBuilder.reflectionEquals(this, obj);
}

@Override
public String toString()
{
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}


Finally, if you use JAXB 2.x to generate Java classes from XML Schema, make sure you use jaxb2-commons's jakarta-commons-lang plugin to generate these methods. I have painful memory of working with plain JAB2-generated classes in unit testing before I discovered this precious plugin, which inspired me to write this post entry to share the simplest way to override hasCode(), equals(Object) and toString() methods with you....

Monday, December 29, 2008

Preventing NullPointerException

When a NullPointerException (NPE) is thrown, it can be hard to trace back to the bug that causes it, especially if it comes from an instance variable of a mutable class, where the execution of buggy code may have finished long before the NPE is thrown. With the wide adoption of the best practice of immutability and IoC container, it is not seen as frequently as before and most of the time it is easy to locate the bug, such as a missing setter injection in the Spring application context. Probably as a result, recently some developers seem to have relaxed on null checking as I have seem some codes in an open soure project that completely lacks both null checking and documentation of the preconditions on methods.

This week, I have seen two good practices (IMHO) of null checking and related documentation:

The first is a static method named T checkNotNull(T reference, String referenceName) in class Preconditions I found in the Activity Stream project. This class is modelled after a similar class from Google Collections API. Note that it does not share any of its source code.

This reminds me of the static methods void notNull(Object object) and void notNull(Object object, String message) from Validate class in Apache Commons Lang that are used a lot in my previous job for null checking:

import static org.apache.commons.lang.Validate.notNull;
...
public class Foo
{
private final Bar bar;

public Foo(Bar bar)
{
notNull(bar, "Bar must not be null.");
this.bar = bar;
...
}
...
}

The T checkNotNull(T reference, String referenceName) has the advantage of returning the parameter, thus it can be assigned right after the null checking:

import static com.atlassian.streams.util.Preconditions.checkNotNull;
...
public class Foo
{
private final Bar bar;

public Foo(Bar bar)
{
this.bar = checkNotNull(bar, "Bar");
...
}
...
}

Similar to null checking, quite often there is also a need to guard against empty String, blank String (containing only whitespaces, see StringUtils), empty Collection, null-containing Collection (containing a null element), empty Array, null-containing Array and empty Map, etc.

Luckily, Validate provides most of these checks:
  • void notEmpty(Collection collection, String referenceName)
  • void noNullElements(Collection collection, String referenceName)
  • void notEmpty(String string, String referenceName)
  • void notEmpty(Object[] array, String referenceName)
  • void noNullElements(Object[] array, String referenceName)
  • void notEmpty(Map map, String referenceName)

Unfortunately, they all return void and cannot be chained, and it can force you to write your own little static method to do all the checks, or use it before the proper check:

import static org.apache.commons.lang.Validate.*;
...
public class Foo extends Bar
{
public Foo(List list)
{
super(notEmptyNoNullElements(list));
}

private static notEmptyNoNullElements(Collection collection)
{
notEmpty(collection);
noNullElements(collection);
}
...
}

So I have added the following methods to Preconditions:
  • <T, C extends Collection<T>> C notEmpty(C collection, String name)
  • <T, C extends Collection<T>> C noNullElements(C collection, String name)
  • <T, C extends Collection<T>> C notEmptyNoNullElements(C collection, String name)
  • <T> T[] notEmpty(T[] array, String name)
  • <T> T[] noNullElements(T[] array, String name)
  • <T> T[] notEmptyNoNullElements(T[] array, String name)
  • <K, V> Map<K, V> notEmpty(Map<K, V> map, String name)
  • String notBlank(String text, String name)

The other example is actually in the Google Gadgets API. All the optional parameters are prefixed with "opt_", making it very obvious. So instead of just documenting in javadoc, we can also given a more intention-revealing name to parameters, such as:

/**
* Do something.
* @param bar Used to do something. Cannot be <code>null</code>. Mandatory...
* @param baz Used to do something. Can be <code>null</code>. Optional...
*/
public void foo(Bar bar, Baz optBaz)
{
...
}

Finally, Preconditions probably should not sit in streams-core. It would be more useful if it is moved to some core projects, such as atlassian-core, so that different teams do not have to reinvent the wheel.

Wednesday, July 23, 2008

Unable to install equinox p2 plugins for Eclipse Ganymede

I have been trying to install "build utility feature for equinox p2 plugins", on which Spring IDE Eclipse plugin and M2Eclipse plugin have a dependency. But I'm constantly getting an "Invalid zip file format" error:

An error occurred while collecting items to be installed
Error closing the output stream for master-equinox-p2/org.eclipse.update.feature/1.0.0.v20080506-4--8Mc44yANsYbyiqu-z-uDo0 on repository file:/C:/eclipse-3.4-ganymede/.
Error unzipping C:\DOCUME~1\Alex\LOCALS~1\Temp\master-equinox-p2_1.0.0.v20080506-4--8Mc44yANsYbyiqu-z-uDo044914.jar: Invalid zip file format


It seems to be unable to download a good copy of master-equinox-p2 JAR file. I have cleaned up all the temporary internet files and tried to install on a different machine but still no luck. I suspect that the mirror site is corrupted, probably with a bad signature or something. But it doesn't seem to allow me to choose mirror site in Ganymede any more. Urrghh!

Saturday, June 14, 2008

Which is the hottest Java web framework that people want to learn?

A recent post on The "Break it Down" Blog, Which is the Hottest Java Web Framework? Or Maybe Not Java? has attracted lots of attention, including that of Java Web Frameworks Guru Matt Raible.

The author excluded Tapestry and Stripes because of the high noise from the common usage of these terms.

Some readers, including myself, commented that the high search rate may reflect that some frameworks, like JSF, especially JSF 1.1, are so bad that people encounter problems all the time and have to rely on Google to search for solutions.

In order to find out how people really like to learn about those frameworks mentioned in the post, I tweaked the search terms a bit by adding the word "tutorial", as I reckon anyone who wants to learn a web technology is likely to search for a tutorial on that technology, only if they speak English...

And here are the result.

Comparing JSF, Struts 2, Spring MVC / Spring Webflow, JBoss Seam and Apache Wicket:

As we can see, JSF is much more popular than all other Java web frameworks and is very popular in India, Hong Kong, Czech, Singapore and the Philippines. Struts 2 ranked second, slightly better than Spring MVC and Seam. And Wicket didn't even have enough search volume to rank.

Then I compared Struts 2, Spring MVC / Spring Webflow, JBoss Seam, Tapestry and Grails:

Basically, there is little search volume for tutorials on Grails, Tapestry and Stripes (not shown in this image). This is probably an indication that the official website for these frameworks have good documentation and tutorials, where JSF is only a specification and you have to find tutorials elsewhere.

Here the interesting observation is: Struts 2 is very popular in India and Brazil; Seam is far more popular in Austria, Spring MVC is especially popular in London and Grails has been taken up quite well in Germany. And surprsingly, even Australia has more search volumes for these frameworks than the United States.

Finally, I compared Ruby on Rails, Adobe Flex, JSF, Struts 2 and Spring MVC / Spring Webflow:



Hmmm, Ruby on Rails, Adobe Flex and JSF are popular to the same level. However, the popularity of JSF has been on a plateau for the past few years and has begun to decline. Ruby on Rails also starts to show signs of decline, while Flex is rising sharply.

And Ruby on Rails are very popular in San Francisco and San Jose, CA, the Philippines and Sweden. And Flex is rather popular in Brazil and Europe.

Saturday, March 8, 2008

More on How to make Acegi work on Sun Application Server 8.x?

Applying the solution mentioned in my previous post IMHO: How to make Acegi work on Sun Application Server 8.x? has been proved working quite well. Well, until I encountered the same ClassCastException again. This time it was because the access was denied. Looking into the stack trace, I found that it was because Acegi's AccessDeniedHandlerImpl forwards the SecurityContextHolderAwareRequestWrapper to show the error page.

Similar to the solution in the previous post, I creates a NullPrincipalAccessDeniedHandlerImpl, which extends Acegi's AccessDeniedHandlerImpl but wrap the HttpServletRequest with the NullPrincipalHttpServletRequestWrapper.

Following is the source code of NullPrincipalAccessDeniedHandlerImpl:

package au.net.ozgwei.util.spring.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.ui.AccessDeniedHandlerImpl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import au.net.ozgwei.util.httpservlet.NullPrincipalHttpServletRequestWrapper;

/**
* An Acegi AccessDeniedHandler implementation designed specific to get around
* the bug in Sun Application Server 8.x where a custom security framework's
* implementation of Principal is casted to Sun Application Server's own
* implementation.
*
* @author Alex
* @version 1.0
*/
public class NullPrincipalAccessDeniedHandlerImpl extends
AccessDeniedHandlerImpl {

@SuppressWarnings("unused")
private static final Log log =
LogFactory.getTrace(
NullPrincipalAccessDeniedHandlerImpl.class);

/**
* Default no-arg constructor.
*/
public NullPrincipalAccessDeniedHandlerImpl() {
super();
}

@Override
public void handle(ServletRequest aRequest, ServletResponse aResponse,
AccessDeniedException aAccessDeniedException) throws IOException,
ServletException {

super.handle(new NullPrincipalHttpServletRequestWrapper(
(HttpServletRequest)aRequest), aResponse, aAccessDeniedException);
}

}

Of course, the Spring application context must be changed to replace the original AccessDeniedHandler implementation with this in the definition of the exceptionTranslationFilter bean:
<bean id="exceptionTranslationFilter"
class="org.acegisecurity.ui.ExceptionTranslationFilter">
<property name="authenticationEntryPoint">
<ref local="authenticationProcessingFilterEntryPoint"/>
</property>

<property name="accessDeniedHandler">
<bean class="au.com.cardlink.common.util.spring.security.NullPrincipalAccessDeniedHandlerImpl">
<property name="errorPage" value="/faces/ForbiddenAccess.jsp"/>
</bean>
</property>

</bean>

Now it works even if user's access to a protected URL is denied by Acegi.

Friday, February 22, 2008

12 Technologies I Would Like to Grasp in 2008

  1. Grails
  2. Groovy
  3. OSGi
  4. Spring Batch
  5. Spring Security 2.0
  6. Spring Web Services
  7. AspectJ
  8. JBoss Seam
  9. RichFaces
  10. Mule
  11. JavaFX
  12. Selenium

Wednesday, February 6, 2008

Grails 1.0 is Out!

Grails 1.0 was finally released yesterday!
To quote from the official website: "The Search Is Over!"
After a long and exciting wait, Grails, the response to Ruby on Rails (RoR) from the Java land, has reached maturity.
It adopts "Convention over Configuration" (CoC), which has been made popular by RoR.
It's built on top of solid frameworks, such as Spring, Hibernate & Sitemesh, allowing developers to quickly develop web application with a focus on CRUD operations on database.
It also has a healthy plugin system to allow contributors to develope plugins, such as Acegi plugin.
When developing with Grails, you program in Groovy, a powerful scripting language that runs seamlessly on the JVM. It has all the powers that Ruby has and maybe more.
Enjoy the journey to Grails! I'm sure I will.

Monday, January 21, 2008

How to make Acegi work on Sun Application Server 8.x?

We are currently developing an application that employs Acegi and runs on Sun Application Server 8 (Sun AS 8.x).

Being a mature and widely adopted security solution, we did not have many problems until we encountered the following puzzling exception:
[#|2008-01-18T16:58:28.984+1100|SEVERE|sun-appserver-pe8.2|javax.enterprise.system.container.web|_ThreadID=22;|ApplicationDispatcher[/express_portal] Servlet.service() for servlet jsp threw exception
java.lang.ClassCastException: org.acegisecurity.providers.UsernamePasswordAuthenticationToken
at com.sun.web.server.J2EEInstanceListener.handleBeforeEvent(J2EEInstanceListener.java:130)
at com.sun.web.server.J2EEInstanceListener.instanceEvent(J2EEInstanceListener.java:68)
at org.apache.catalina.util.InstanceSupport.fireInstanceEvent(InstanceSupport.java:300)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:482)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:417)
at org.apache.catalina.core.ApplicationDispatcher.access$000(ApplicationDispatcher.java:80)
at org.apache.catalina.core.ApplicationDispatcher$PrivilegedForward.run(ApplicationDispatcher.java:95)
at java.security.AccessController.doPrivileged(Native Method)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:313)
at org.acegisecurity.ui.AccessDeniedHandlerImpl.handle(AccessDeniedHandlerImpl.java:65)
at org.acegisecurity.ui.ExceptionTranslationFilter.handleException(ExceptionTranslationFilter.java:166)
at org.acegisecurity.ui.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
at org.acegisecurity.providers.anonymous.AnonymousProcessingFilter.doFilter(AnonymousProcessingFilter.java:125)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
at org.acegisecurity.wrapper.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:81)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:217)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
at org.acegisecurity.ui.logout.LogoutFilter.doFilter(LogoutFilter.java:106)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
at org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:229)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
at org.acegisecurity.concurrent.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:95)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
at org.acegisecurity.util.FilterChainProxy.doFilter(FilterChainProxy.java:148)
at org.acegisecurity.util.FilterToBeanProxy.doFilter(FilterToBeanProxy.java:98)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationFilterChain.access$000(ApplicationFilterChain.java:55)
at org.apache.catalina.core.ApplicationFilterChain$1.run(ApplicationFilterChain.java:161)
at java.security.AccessController.doPrivileged(Native Method)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:263)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:551)
at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:173)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:551)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:551)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:132)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:551)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:933)
at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:189)
at com.sun.enterprise.web.connector.grizzly.ProcessorTask.doProcess(ProcessorTask.java:604)
at com.sun.enterprise.web.connector.grizzly.ProcessorTask.process(ProcessorTask.java:475)
at com.sun.enterprise.web.connector.grizzly.ReadTask.executeProcessorTask(ReadTask.java:371)
at com.sun.enterprise.web.connector.grizzly.ReadTask.doTask(ReadTask.java:264)
at com.sun.enterprise.web.connector.grizzly.TaskBase.run(TaskBase.java:281)
at com.sun.enterprise.web.connector.grizzly.WorkerThread.run(WorkerThread.java:83)
|#]


We traced the application server and found that it was likely caused by the Sun AS 8.x trying to cast the Acegi-implemented Principal to an internal Sun AS implementation.

We did some googling and found that Andrey Grebnev blogged about this two years ago, and he suggested a workaround by overriding the getUserPrincipal() method (of SecurityContextHolderAwareRequestWrapper) by always returning a null.

Because SecurityContextHolderAwareRequestWrapper and its subclasses are used internally by Acegi, his workaround implied changing the source code of Acegi, which we are reluctant to do.

Realizing that the it was only unsafe for the HttpServletRequest to return the Acegi-implemented Principal when the servlet filter chain has been executed and the control is handed over to the AS and the running application, we came up with a NullPrincipalFilter that wraps the incoming HttpServletRequest with a NullPrincipalHttpServletRequestWrapper, which returns null for getUserPrincipal(), and hands the control over to the AS. This filter should always be placed at the end of the filter proxy chain in Acegi. And of course, the application must not use HttpServletRequest's getUserPrincipal() method to retrieve the user principal, which is very easy to do, as it can invoke SecurityContextHolder.getContext().getAuthentication() to achieve the same goal, without coupling to the Servlet API.

The following is the source code of NullPrincipalFilter:

package au.net.ozgwei.util.httpservlet;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* A filter designed specific to get around the bug in Sun Application Server
* 8.x where a custom security framework's implementation of Principal is
* casted to Sun Application Server's own implementation.
*
* @author Alex
* @version 1.0
*/
public class NullPrincipalFilter implements Filter {

@SuppressWarnings("unused")
private static final Log log = LogFactory.getLog(NullPrincipalFilter.class);

/* (non-Javadoc)
* @see javax.servlet.Filter#destroy()
*/
public void destroy() {
}

/* (non-Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest aRequest, ServletResponse aResponse, FilterChain aFileterChain) throws IOException, ServletException {
aFileterChain.doFilter(
new NullPrincipalHttpServletRequestWrapper(
(HttpServletRequest) aRequest), aResponse);
}

/* (non-Javadoc)
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig aArg0) throws ServletException {
}

}


And the source code of NullPrincipalHttpServletRequestWrapper:

package au.net.ozgwei.util.httpservlet;

import java.security.Principal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* A HttpServletRequestWrapper that always return null for Principal.
*
* @author Alex
* @version 1.0
*/
public class NullPrincipalHttpServletRequestWrapper extends HttpServletRequestWrapper {

@SuppressWarnings("unused")
private static final Log log = LogFactory.getLog(
NullPrincipalHttpServletRequestWrapper.class);

public NullPrincipalHttpServletRequestWrapper(HttpServletRequest aReq) {
super(aReq);
}

@Override
public Principal getUserPrincipal() {
return null;
}

}


And a nullPrincipalFilter bean should be defined in the Spring application context and added to the end of the filterChainProxy, as following:
<bean class="org.acegisecurity.util.FilterChainProxy" id="filterChainProxy">
<property name="filterInvocationDefinitionSource">
<value>
CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
PATTERN_TYPE_APACHE_ANT
/**=concurrentSessionFilter,httpSessionContextIntegrationFilter,logoutFilter,authenticationProcessingFilter,securityContextHolderAwareRequestFilter,anonymousProcessingFilter,exceptionTranslationFilter,filterInvocationInterceptor,nullPrincipalFilter
</value>
</property>
</bean>

<bean class="au.net.ozgwei.util.httpservlet.NullPrincipalFilter" id="nullPrincipalFilter">


Finally, this bug has been fixed in GlassFish eventually.

Wednesday, January 16, 2008

Gavin King: first impression (contrasting Spring guys)

Today I attended Red Hat's "Gavin King" event. While I have attended many Spring events in Sydney, this is my first time attending a Hibernate/JBoss/Red Hat event. And the impressions are quite different...

  • First impression - clothes:
    • The Spring guys are always well-suited and businessmen-like. They are often the centre of the crowd.
    • Gavin's clothes were the most casual in the room. Before his presentation, I thought that fitted T-shirt wearing guy in trendy jeans was some skateboarding Ruby programmer who happened to want to know something in the Java world...
  • Presentation style:
    • The presentations by the Spring guys are always very professional, with the right level in technology details according to the nature of the event, the structure well organised, and seemingly well rehearsed.
    • Gavin's presentation is, again, more casual, just like a technology chat. I don't know how much the other people in the audience know about Web Beans and Seam, but Gavin lost me a few times because I haven't been following what's happening in the JBoss world...
  • Technology inclination:
    • The Spring guys can be very pedantic (in a good way), always emphasising best practices, such as programming to interfaces, abstraction levels, separation of concerns, etc.
    • Gavin is more pragmatic. Interfaces did not even make it to his slides. His Web Beans JSR recommends to make business interface optional for EJB 3.1 in Java EE 6. He reckons AOP is too complex for ordinary Java developers, there are only a handful of cross-cutting concerns, and EJB interceptors are enough to get the job done.
    • Spring framework focuses on enterprise applications that are typically developed by financial institutions and usually involves lots of web services and enterprise application integration, and some of these enterprise applications may not even have a web tier.
    • Web Beans JSR, JBoss Seam and Rich Faces, promoted by Gavin, are all mostly relevant to web-focused projects. Web Beans and JBoss Seam are particularly designed to ease development burden on entity management website with lots of CRUD operations, which make them competitors of (J)Ruby on Rails and Grails. I'll try to compare these frameworks in a later post. Enterprise applications seem off the target.
    • The apparent weakness in the Spring framework are: no type-safety check in the application context until runtime, verbose XML configuration, no bean id (or name) namespaces and the statelessness of Spring-managed beans. However, the first two have been addressed by JavaConfig and XML namespace. Noticeably, JavaConfig also uses annotations, but only in the config class without polluting the service bean or the service client. The stateless singleton issue has also been tackled with 'scopes' and domain object dependency injection, which is enabled by Spring AOP.
    • Gavin loves type-safety check in Java, so he hates the lack of type-safety check in Spring XML configuration, and he embraces annotation wholeheartedly. So he prefers Google Guice to Spring for dependency injection. In contrast to Spring's JavaConfig, Google Guice's annotations are used everywhere, in the service bean, in the service client or both. JBoss Seam introduces lots of annotations, and Web Beans JSR is to make many of these annotations into Java EE standard. I don't remember how many times Gavin showed the definition of an annotation in his slides today. Probably a dozen! And he still relies on XML configuration to override annotations. He classifies services beans according to deployment, such as one for production, one for stubbing in testing. So what will you do if you have two classes with the same service API, both used in production environment? My guess is you need to write a new annotation to differentiate them... Seems overuse of annotations, doesn't it?
  • Hostility:
    • Spring guys rarely publicly show their hostility towards JBoss, though in after session chats, they describe JBoss Seam as a "big hack", "annotation hell", "technologically inferior" and "would have been just another web framework were it not for Gavin King's fame".
    • Gavin is more straight forward, rubbished Spring guys as "AOP nerds" during the session, and I wouldn't be surprised if he called Spring "XML hell". He deliberately omitted Spring when he enumerated the open source frameworks that have influenced Java EE.
  • The audience:
    • Spring events usually draw a huge audience. Many times, some people who came late had to stand in the back of the room for the whole session. They are almost always held in the evening.
    • Today's Hibernate event was held in the morning with only a few dozen people attending. One-third of the seats were empty.

Anyway, I was pretty impressed by Gavin's demo of fast web project development with JBoss AS, JBoss Seam, Rich Faces and JBoss Tools. I'll definitely give it a try when I have the time...

Monday, December 31, 2007

Hibernate: how to map a collection of embedded components keyed by one of the component's properties?

Quite often, during application development, I encounter the issue of mapping a collection of embedded components using Hibernate.

An embedded component is, in Hibernate, a user-defined value-typed class. It has no individual identity, hence the persistent component class requires no identifier property or identifier mapping; its lifespan is bounded by the lifespan of the owning entity instance.

When mapping a collection of embedded components, it is very important to override the equals() and hashCode() methods and compare all properties, because they are used by Hibernate to detect modifications to these components.

Very often, this collection of components also has a unique key property, that is, the collection should normally be implemented as a map indexed by the value of the key property.

The book "Java Persistence with Hibernate" and Hibernate's documentation illustrate 3 ways to map a collection of embedded components.

The first and highly recommended (by Hibernate) option is to map the collection to a set. This method requires all database columns mapped to the component class must be declared with not-null="true". It does not address the key property issue, either. I myself often find it unwieldy when dealing with the key property because it becomes my responsibility to enforce the map semantics. For example, when adding a new element, I need to iterate the set and find the existing element having the same key property value with the new element. If the existing element is found, depending on the business rule, I may throw an exception, or remove the existing element from the set and add the new element in. When you have several entity classes that have component map, you have to duplicate the same set iteration logic in many places...

The second option is to map the collection to an idbag. Again, it is the responsibility of my application to ensure the map semantics.

The third option is to map it to a map. Unfortunately, this option requires the removal of the key property from the component class. The following is the example extracted from the above-mentioned book to demonstrate the mapping of the images belonging to an item in the Caveate Emptor sample application, where the image name must be unique.

<map name="images"
table="ITEM_IMAGE"
order-by="IMAGENAME asc">

<key column="ITEM_ID"/>
<map-key type="string" column="IMAGENAME"/>
<composite-element class="Image">
<property name="filename" column="FILENAME" not-null="true"/>
<property name="sizeX" column="SIZEX"/>
<property name="sizeY" column="SIZEY"/>
</composite-element>
</map>

As can be seen from the mapping file snippet above, the "Image" component class no longer has a "name" property. This removal can be quite problematic. The key property is usually the most important property of a component class; removing this property from the component class and handle it merely as a map key not only potentially violates object oriented technology principles theoretically, but also can have significant consequences in practice. For example, the public interface of the entity class may need to be overhauled. Instead of an addImage(Image image) method, you need to provide an addImage(String imageName, Image image) method. Or, you have to create another value-type class just in order to wrap the name-deprived Image and the image name together.

Luckily, Hibernate 3.x provides a very powerful new feature called formula. This can easily solve our dilemma. It can map the component map to a map, but it does not require the removal of the key property from the component class. With formula, the above mapping can be modified to:

<map name="images"
table="ITEM_IMAGE"
order-by="IMAGENAME asc">

<key column="ITEM_ID"/>
<map-key type="string" column="IMAGENAME"/>
<composite-element class="Image">
<property name="name" type="string" formula="IMAGENAME"/>
<property name="filename" column="FILENAME" not-null="true"/>
<property name="sizeX" column="SIZEX"/>
<property name="sizeY" column="SIZEY"/>
</composite-element>
</map>

In short, it allows the "IMAGENAME" column to be mapped to both the map key and the key property of the "Image" class when loading from database. When persisting, only the map key is used to update the "IMAGENAME" column.

Now we can map a map of embedded components to a map without sacrificing the key property or writing messy codes to enforce map semantics...

Friday, November 2, 2007

classpath*:BeanRefFactory.xml not found when instantiating a singleton Spring application context inside EJB2.x running on Sun application server 8.2

For the project I'm currently working on, we use Spring's EJB support. In order to share application context among all EJB instances, SingletonBeanFactoryLocator is used to locate or load the shared application context. And we used the default "classpath*:beanRefFactory.xml" selector key.

However, when the EJB is deployed and invoked, a FatalBeanException is thrown stating
Unable to find resource for specified definition. Group resource name
[classpath*:beanRefFactory.xml], factory key [...]


Looking into the implementation of SingletonBeanFactoryLocator, we found that it delegates to PathMatchingResourcePatternResolver to load the XML file. If the resource starts with "classpath*:" prefix, it uses ClassLoader's getResources(String) method to load the resource; otherwise, a ClasspathResource is returned, which eventually uses ClassLoader's getResource(String) method to load the resource. Pay attention to the plural form of the method name.

In the base java.lang.ClassLoader, both getResource(String) and getResources(String) delegate to its parent first. If the resource is not found by the parent, it invokes findResource(String) and findResources(String) methods, both of which simply return null. The Javadoc of ClassLoader recommends that, for both finder methods:
Class loader implementations should override this method to specify where to
load resources from.


However, when tracing the execution in debug mode, we found that the EJBClassLoader used by Sun Application Server 8.2 only overrides findResource(String) method and searches for the resource in the expanded directory of the EJB Jar file; it does not override findResources(String), which remains returning null, against their own advice.

Now it's obvious, this is due to a defect in Sun Application Server 8.2. The simplest solution is to specify the selector key as "classpath:beanRefFactory.xml" instead of the default value.

Saturday, October 27, 2007

Integrating Spring, Hibernate and EJB 2.x

How to configure Hibernate Session Factory in a Spring application context used in an EJB 2.x stateless session bean?

Most of the examples found on the internet about Hibernate and Spring integration are targeted at web applications. How to configure Hibernate and Spring inside an EJB 2.x stateless session bean is rarely mentioned, and it is not as simple and straightforward as many assume.

The most important issue of the integration is around the management of JDBC connections:
In EJB 2.x, JDBC connections are managed by the data source registered with JNDI on the application server:

  • Applications are not expected to hold on JDBC connections after each use, that is, applications should aggressively release JDBC connections, preferrably after each statement.

  • Applications can acquire JDBC connections multiple times during the execution of one EJB invocation. The application server may return the same JDBC connection, or it may return different JDBC connections, but it assures that all JDBC connections returned are registered within the same Container Managed Transaction.


When database is accessed outside EJB 2.x, such as in a web application running in Tomcat, the application itself is responsible for transaction demarcation. When using a local database transaction, the application code must ensure that the same JDBC connection be used in all database access within the same transaction. Because database access occurs in multiple classes that collaborate to complete a transaction, it is very unwieldy for applications to pass around the JDBC connection in order to re-use the same JDBC connection.

Enter Spring and Hibernate.

Spring guarantees the same JDBC connection is reused, provided the same Spring-managed data source is re-used. The magic happens when a JDBC connection is retrieved for the first time from a Spring-managed data source, Spring binds the JDBC connection to the current execution thread. When another JDBC connection is requested within the same transaction from the Spring-managed data source, Spring returns the thread-bound JDBC connection. When the transaction ends, Spring invokes the commit() or rollback() method of the thread-bound JDBC connection and then unbinds it from the thread.

Hibernate 3.x employs similar technique. By default, a Hibernate session is bound to the thread and returned whenever SessionFactory.getCurrentSession() is invoked within the same transaction. The same JDBC connection is used for all JDBC operations initiated by the same Hibernate session. It is possible to specify other current session context class other than the default thread local context since Hibernate 3.1.

As can be seen from the above discussion, Spring and Hibernate by default re-use the same thread-bound JDBC connection. This setting does not go well with the aggressive connection release mode expected by EJB 2.x. Therefore, non-default settings must be configured for both Spring and Hibernate for Spring and Hibernate combination to be integrated within EJB 2.x.

Below is the recommended configuration. The reasons behind this configuration are explained following the configuration.

<jee:jndi-lookup id="dataSource"
jndi-name="jdbc/datasource" resource-ref="true"/>

<bean id="transactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager"/>

<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- default value is "false"
<property name="useTransactionAwareDataSource" value="false"/>
-->
<property name="exposeTransactionAwareSessionFactory" value="false"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SomeDialect</prop>
<!--
WARNING! 'hibernate.connection.release_mode' must not be set to
'after_statement'. Otherwise, it will be overriden with 'after_transaction'
by Hibernate because Spring's LocalConnectionProvider does not support
aggressive connection release.
-->
<prop key="hibernate.connection.release_mode">auto</prop>
<prop key="hibernate.current_session_context_class">jta</prop>
<prop key="hibernate.transaction.manager_lookup_class">org.hibernate.transaction.SunONETransactionManagerLookup</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.CMTTransactionFactory</prop>
<prop key="hibernate.transaction.flush_before_completion">true</prop>
<prop key="hibernate.transaction.auto_close_session">true</prop>
</props>
</property>
<property name="mappingResources">
<list>...</list>
</property>
</bean>


The reasons behind this configuration are explained below. It is recommended to have your IDE opened and source code of Spring and Hibernate 3.1 or above ready.

Spring uses LocalSessionFactoryBean, which is a subclass of AbstractSessionFactoryBean, to configure a Hibernate session factory.

There are lots of javadoc to read for each bean property that can be set for a LocalSessionFactoryBean. It's better off to read the buildSessionFactory() method to understand what each property value does in the build time.

Note that the above configuration has two parts for LocalSessionFactoryBean, the 'normal' Spring bean properties, such as 'dataSource', and the 'hibernateProperties' that takes a java.util.Properties value. The 'normal' properties are used to configure the default settings, which can be overriden by the 'hibernateProperties'.

As a side note, we don't set the 'jtaTransactionManager' property. Note that the class for this property is javax.transaction.TransactionManager, not the JtaTransactionManager that implements Spring's PlatformTransactionManager. In order to set this property, we need to know the JNDI name that the target application server binds its JTA transaction manager. The benefit of setting this property would be that we don't need to configure Hibernate's 'hibernate.transaction.manager_lookup_class' and 'hibernate.transaction.factory_class' properties. We concluded that this benefit could not justify explicitly specifying the application server specific JNDI name for transaction manager. We would rather set those two properties in Hibernate configuration.

If 'jtaTransactionManager' property is not set, Spring automatically set the 'hibernate.connection.release_mode' property to 'on_close'. Because we are running Hibernate inside an EJB 2.x, we must set this property to other value in the overriding 'hibernateProperties'.

The 'exposeTransactionAwareSessionFactory' property has a default value of true. If set to true, Spring will set the 'hibernate.current_session_context_class' property to Spring's own thread-bound implementation, which must be overriden by a value of 'jta' in the 'hibernateProperties'.

The 'useTransactionAwareDataSource' property must be left to the default 'false' value. Otherwise, Spring will wrap the data source with a TransactionAwareDataSourceProxy, which will effectively re-use the same JDBC transaction within the same transaction, even if Hibernate aggressively releases connections.

It must be pointed out that when 'useTransactionAwareDataSource' is set to false, Spring will supply LocalDataSourceConnectionProvider as the implementation of Hibernate's ConnectionProvider. LocalDataSourceConnectionProvider informs Hibernate that it does not support aggressive release of connection. However, in Hibernate's SettingsFactory, if the ConnectionProvider does not support aggressive release of connections and connection release mode is set to 'after_statement', the connection release mode will be automatically rectified to 'after_transaction', which effectively re-uses the same JDBC transaction for the whole transaction. A warning message "Overriding release mode as connection provider does not support 'after_statement'" is logged. Therefore, the connection release mode in the 'hibernateProperties' must be set to 'auto' instead of 'after_statement'. When the transaction factory is set to 'CMTTransactionFactory', the default connection release mode is 'after_statement', which is precisely what we want.

The other property settings are self-explanatory:

  • 'hibernate.current_session_context_class' should be set to 'jta'.

  • 'hibernate.transaction.manager_lookup_class' should be set the a class mapped to the target application server.

  • 'hibernate.transaction.factory_class' should be set to 'org.hibernate.transaction.CMTTransactionFactory'.


I hope this post will help anyone who has encountered mysterious connection problems when integrating Spring, Hibernate and EJB 2.x

Thursday, October 25, 2007

Cryptic JTS5031 and JTS5068 errors on Sun Application Server 8.1 and 8.2

We encountered the following exceptions when testing our EJB 2.1 + Spring + Hibernate + Osworkflow (also using Hibernate) application.

When running on Sun Application Server 8.1 EE, the stack trace is listed below:
[#2007-10-25T10:50:34.347+1000FINEsun-appserver-ee8.1_02javax.enterprise.resource.jta_ThreadID=13;TM: enlistComponentResources#]
[#2007-10-25T10:50:34.400+1000FINEsun-appserver-ee8.1_02javax.enterprise.resource.jta_ThreadID=13;--Created new J2EETransaction, txId = 25#]
[#2007-10-25T10:50:34.400+1000FINEsun-appserver-ee8.1_02javax.enterprise.resource.jta_ThreadID=13;TM: enlistComponentResources#]
[#2007-10-25T10:50:34.401+1000FINEsun-appserver-ee8.1_02javax.enterprise.resource.jta_ThreadID=13;
In J2EETransactionManagerOpt.enlistResource, h=5 h.xares=com.sun.gjc.spi.XAResourceImpl@c21e52 h.alloc=com.sun.enterprise.resource.ConnectorAllocator@54d24d tx=J2EETransaction: txId=25 nonXAResource=null jtsTx=null localTxStatus=0 syncs=[]#]
[#2007-10-25T10:50:34.401+1000FINEsun-appserver-ee8.1_02javax.enterprise.resource.jta_ThreadID=13;TM: begin#]
[#2007-10-25T10:50:34.402+1000FINEsun-appserver-ee8.1_02javax.enterprise.system.core.transaction_ThreadID=13;Control object :com.sun.jts.CosTransactions.ControlImpl@162aeda corresponding to this transaction has been createdGTID is : 19000000BBF79CD4616476627661707030312C5033373030#]
[#2007-10-25T10:50:34.402+1000FINEsun-appserver-ee8.1_02javax.enterprise.resource.jta_ThreadID=13;TM: enlistResource#]
[#2007-10-25T10:50:34.402+1000FINEsun-appserver-ee8.1_02javax.enterprise.resource.jta_ThreadID=13;--In J2EETransaction.enlistResource, jtsTx=com.sun.jts.jta.TransactionImpl@ffe966e9 nonXAResource=null#]
[#2007-10-25T10:50:34.404+1000FINEsun-appserver-ee8.1_02javax.enterprise.resource.jta_ThreadID=13;--In J2EETransaction.registerSynchronization, jtsTx=com.sun.jts.jta.TransactionImpl@ffe966e9 nonXAResource=null#]
[#2007-10-25T10:50:34.405+1000FINEsun-appserver-ee8.1_02javax.enterprise.resource.jta_ThreadID=13;--In J2EETransaction.registerSynchronization, jtsTx=com.sun.jts.jta.TransactionImpl@ffe966e9 nonXAResource=null#]
[#2007-10-25T10:50:34.406+1000FINEsun-appserver-ee8.1_02javax.enterprise.resource.jta_ThreadID=13;TM: delistResource#]
[#2007-10-25T10:50:34.406+1000FINEsun-appserver-ee8.1_02javax.enterprise.resource.jta_ThreadID=13; ejbDestroyed: AccountProcessServiceBean; id: [B@7219a#]
[#2007-10-25T10:50:34.406+1000FINEsun-appserver-ee8.1_02javax.enterprise.resource.jta_ThreadID=13;TM: rollback#]
[#2007-10-25T10:50:34.406+1000FINEsun-appserver-ee8.1_02javax.enterprise.system.core.transaction_ThreadID=13;Within TopCoordinator.rollback() :GTID is : 19000000BBF79CD4616476627661707030312C5033373030#]
[#2007-10-25T10:50:34.409+1000SEVEREsun-appserver-ee8.1_02javax.enterprise.system.core.transaction_ThreadID=13;JTS5031: Exception [org.omg.CORBA.INTERNAL: vmcid: 0x0 minor code: 0 completed: Maybe] on Resource [rollback] operation.#]
[#2007-10-25T10:50:34.410+1000FINEsun-appserver-ee8.1_02javax.enterprise.system.container.ejb_ThreadID=13;context with empty container in ContainerSynchronization.afterCompletion#]
[#2007-10-25T10:50:34.410+1000FINEsun-appserver-ee8.1_02javax.enterprise.system.core.transaction_ThreadID=13;Within TopCoordinator.rollback() :GTID is : 19000000BBF79CD4616476627661707030312C5033373030#]
[#2007-10-25T10:50:34.411+1000FINEsun-appserver-ee8.1_02javax.enterprise.system.container.ejb_ThreadID=13;EJB5092:Exception occurred in postInvokeTx : [{0}]
javax.transaction.SystemException: org.omg.CORBA.INTERNAL: JTS5031: Exception [org.omg.CORBA.INTERNAL: vmcid: 0x0 minor code: 0 completed: Maybe] on Resource [rollback] operation. vmcid: 0x0 minor code: 0 completed: No
at com.sun.jts.jta.TransactionManagerImpl.rollback(TransactionManagerImpl.java:295)
at com.sun.enterprise.distributedtx.J2EETransactionManagerImpl.rollback(J2EETransactionManagerImpl.java:1054)
at com.sun.enterprise.distributedtx.J2EETransactionManagerOpt.rollback(J2EETransactionManagerOpt.java:391)
at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:2711)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:2521)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:819)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:137)
at $Proxy22.processUser(Unknown Source)
at au.net.ozgwei.services.userprocess.UserProcessServiceDelegate.processUser(UserProcessServiceDelegate.java:96)
...
[#2007-10-25T10:50:34.414+1000INFOsun-appserver-ee8.1_02javax.enterprise.system.container.ejb_ThreadID=13;EJB5018: An exception was thrown during an ejb invocation on [UserProcessServiceBean]#]


When running on Sun Application Server 8.2 PE, the stack trace is listed below:
[#2007-10-25T17:52:04.079+1000INFOsun-appserver-pe8.2javax.enterprise.system.stream.out_ThreadID=14;454609 [httpWorkerThread-2189-4] INFO  org.hibernate.impl.SessionFactoryObjectFactory  - Not binding factory to JNDI, no JNDI name configured
#]
[#2007-10-25T17:52:04.079+1000INFOsun-appserver-pe8.2javax.enterprise.system.stream.out_ThreadID=14;454609 [httpWorkerThread-2189-4] INFO org.hibernate.util.NamingHelper - JNDI InitialContext properties:{}
#]
[#2007-10-25T17:52:04.079+1000INFOsun-appserver-pe8.2javax.enterprise.system.stream.out_ThreadID=14;454609 [httpWorkerThread-2189-4] INFO org.springframework.context.support.ClassPathXmlApplicationContext - Bean 'siteManagerSessionFactory' is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
#]
[#2007-10-25T17:52:04.110+1000INFOsun-appserver-pe8.2javax.enterprise.system.stream.out_ThreadID=14;454640 [httpWorkerThread-2189-4] INFO org.springframework.context.support.ClassPathXmlApplicationContext - Bean 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor' is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
#]
[#2007-10-25T17:52:04.110+1000INFOsun-appserver-pe8.2javax.enterprise.system.stream.out_ThreadID=14;454640 [httpWorkerThread-2189-4] INFO org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1956ba5: defining beans [siteManager,siteRepository,siteAssembler,org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor,dataSource,transactionManager,siteManagerSessionFactory,eventLogService]; root of factory hierarchy
#]
[#2007-10-25T17:52:05.207+1000INFOsun-appserver-pe8.2javax.enterprise.system.stream.out_ThreadID=14;455737 [httpWorkerThread-2189-4] INFO org.springframework.transaction.jta.JtaTransactionManager - Using JTA UserTransaction: com.sun.enterprise.distributedtx.UserTransactionImpl@ad9064
#]
[#2007-10-25T17:52:05.207+1000INFOsun-appserver-pe8.2javax.enterprise.system.stream.out_ThreadID=14;455737 [httpWorkerThread-2189-4] INFO org.springframework.transaction.jta.JtaTransactionManager - Using JTA TransactionManager: com.sun.ejb.containers.PMTransactionManagerImpl@1eafdce
#]
[#2007-10-25T17:52:26.027+1000WARNINGsun-appserver-pe8.2javax.enterprise.system.core.transaction_ThreadID=15;JTS5068: Unexpected error occurred in rollback
java.lang.NullPointerException
at com.sun.gjc.spi.ManagedConnection.transactionCompleted(ManagedConnection.java:429)
at com.sun.gjc.spi.XAResourceImpl.rollback(XAResourceImpl.java:140)
at com.sun.jts.jta.TransactionState.rollback(TransactionState.java:168)
at com.sun.jts.jtsxa.OTSResourceImpl.rollback(OTSResourceImpl.java:271)
at com.sun.jts.CosTransactions.RegisteredResources.distributeRollback(RegisteredResources.java:971)
at com.sun.jts.CosTransactions.TopCoordinator.rollback(TopCoordinator.java:2240)
at com.sun.jts.CosTransactions.CoordinatorTerm.rollback(CoordinatorTerm.java:504)
at com.sun.jts.CosTransactions.TerminatorImpl.rollback(TerminatorImpl.java:266)
at com.sun.jts.CosTransactions.CurrentImpl.rollback(CurrentImpl.java:728)
at com.sun.jts.jta.TransactionManagerImpl.rollback(TransactionManagerImpl.java:308)
at com.sun.enterprise.distributedtx.J2EETransactionManagerImpl.rollback(J2EETransactionManagerImpl.java:1058)
at com.sun.enterprise.distributedtx.J2EETransactionManagerOpt.rollback(J2EETransactionManagerOpt.java:391)
at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:2711)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:2521)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:819)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:137)
at $Proxy22.processUser(Unknown Source)
at au.net.ozgwei.services.userprocess.UserProcessServiceDelegate.processUser(UserProcessServiceDelegate.java:96)

These exceptions were really frustrating as they appeared to occur only at transaction commit time that somehow the commit failed and the EJB container was trying to roll back and then encountered an unexpected CORBA or null pointer error.

That led us to think that our configuration for Spring and Hibernate to work with EJB 2.1 was not set up properly.

Well, all that was just red herring. With debugging turned on, it was clear to us that a minor and seemingly innocent change in the web tier resulted in invoking the EJB with illegal arguments and that the POJO implementation wrapped by the EJB threw an IllegalArgumentException, which was swallowed by Sun's EJB container and triggered the transaction to be rolled back.

Once we fixed the bug at the web tier, the issue went away immediately.

So, the problem is with Sun's EJB container: when it catches a runtime exception, it should have printed the stack trace of the root cause of the exception instead of swallowing it. It wasted us several hours to figure out what went wrong.

It also taught us a few lessons:

  1. Debug early on may save you many hours of code reading and googling for a problem that was hidden/eclipse by a seemingly complex problem.
  2. Write more test cases for web tier codes, preferably with EasyMock 2 or jMock 2. If we had written the test cases for the UI, this problem would probably occur in the first place.

So, if you see similar JTS5031 or JTS5068 errors on Sun Application Server 8.x, make sure you do some debugging to verify that it was not caused by a runtime exception thrown by your application code...

Friday, September 28, 2007

Spring 2.0 schemas not found? And the solution is...

We've experienced a mysterious problem that the Spring 2.0 schemas could not be found when the application context is being created inside an EJB 2.1, using Spring's AbstractStatelessSessionBean.

The problem manifests itself with the following exception:
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 18 in XML document from class path resource [springContext.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'beans'.
Caused by:
org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'beans'.
at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at org.apache.xerces.util.ErrorHandlerWrapper.error(Unknown Source)


Normally this is caused by the incorrect XML namespace or schema location declaration at the head of the application context. However, in our case, the declaration was correct:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
...
</bean>


After some research, we found that other people have also experienced this problem.

The cause is that somehow the "META-INF/spring.schemas" and "META-INF/spring.handlers" files packaged in spring.jar could not be found.

What are these two files?
  • "spring.schemas" specifies the classpaths of all Spring schemas within the spring.jar. The content of this file is listed below:

http\://www.springframework.org/schema/beans/spring-beans-2.0.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd
http\://www.springframework.org/schema/tool/spring-tool-2.0.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsd
http\://www.springframework.org/schema/util/spring-util-2.0.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd
http\://www.springframework.org/schema/aop/spring-aop-2.0.xsd=org/springframework/aop/config/spring-aop-2.0.xsd
http\://www.springframework.org/schema/lang/spring-lang-2.0.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd
http\://www.springframework.org/schema/tx/spring-tx-2.0.xsd=org/springframework/transaction/config/spring-tx-2.0.xsd
http\://www.springframework.org/schema/jee/spring-jee-2.0.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd

http\://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd
http\://www.springframework.org/schema/tool/spring-tool.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsd
http\://www.springframework.org/schema/util/spring-util.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd
http\://www.springframework.org/schema/aop/spring-aop.xsd=org/springframework/aop/config/spring-aop-2.0.xsd
http\://www.springframework.org/schema/lang/spring-lang.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd
http\://www.springframework.org/schema/tx/spring-tx.xsd=org/springframework/transaction/config/spring-tx-2.0.xsd
http\://www.springframework.org/schema/jee/spring-jee.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd

  • "spring.handlers" specifies the handler class that implements the NamespaceHandler interface for each namespace. The content of this file is listed below:

http\://www.springframework.org/schema/util=org.springframework.beans.factory.xml.UtilNamespaceHandler
http\://www.springframework.org/schema/aop=org.springframework.aop.config.AopNamespaceHandler
http\://www.springframework.org/schema/lang=org.springframework.scripting.config.LangNamespaceHandler
http\://www.springframework.org/schema/tx=org.springframework.transaction.config.TxNamespaceHandler
http\://www.springframework.org/schema/jee=org.springframework.ejb.config.JeeNamespaceHandler
http\://www.springframework.org/schema/p=org.springframework.beans.factory.xml.SimplePropertyNamespaceHandler

One raised the topic in Spring's support forum that it was because of no internet access for the application server to access the schemas over the internet. Another post even provided a solution to reference the schemas using classpath prefix directly in the application context configuration files.

However, that's not the root cause and a good solution, because even if the application server can access the schemas over the internet or via classpath prefix, the bootstrap code still cannot access the "spring.handlers" file and would not know how to handle various namespaces other than the default "beans".

In fact, the root cause is that the META-INF directory of a can be blocked when referenced inside an EJB jar.

I tried a few ways to get around this problem, and the final solution I adopted is to extract these two files and put them in the META-INF directory of a JAR file that contains only this directory, and place this JAR file in the lib/ext directory of the application server domain where the application is deployed.

I hope this would help others who may face this problem.

Tuesday, September 25, 2007

Nice improvements in NetBeans 6.0

NetBeans 6.0 Beta 1 has been released since last week.

There are a few nice improvements that I have been waiting for:

1) Different font style for different scoped variables.
In NetBeans 5.5.1 and earlier versions, all variables have the default black colour, unlike Eclipse, which displays instance variables in blue and static variables in italic.
NetBeans 6.0 has finally caught up. Now the instance variables are in green and static variables/methods are also italic.

2) Visual JSF page editing now supports message resource bundles.
Previously, when using visual editing of a JSF page, if you need to display a label with text from a resource bundle, you have to manually edit the JSP pages. The resulting components are not displayed on the canvas.
This has been improved. Now these components are displayed on the canvas with the text from the default base.

Nice, isn't it? I may consider switching from MyEclipse to NetBeans 6.0 when it's finally out.

Wednesday, September 19, 2007

Won an IntelliJ IDEA 6.0 licence!

Tonight I went to the Sydney Java User Group's Lightning Talks Night hosted by Atlassian, and won the random audience draw. Among three rewards: a Sun umbrella, a "Java Concurrency in Practice" book and an IntelliJ IDEA licence, I chose IntelliJ IDEA, since: 1) who needs an umbrella in Sydney? 2) I have already got that book, though I haven't started reading...

I used IntelliJ at work previously. But we switched to MyEclipse, mainly because it's easier to find developers with Eclipse experience on the market, and also because the licence is much cheaper.

IntelliJ IDEA is actually a pretty cool IDE. One of the plugins I'd like to try out is the Grails plugin...

I'm also playing with NetBeans 6.0. The beta 1 has just been released.

If I have time, I will try to blog about my experience with these IDEs: Eclipse (and MyEclipse), IDEA and NetBeans...

Tuesday, August 28, 2007

Developer-friendly JAXB code generation with JAXB Commons and binding file

In my previous post "Defining service/component interfaces in WSDLs", I mentioned that "Not only are no-argument constructors and all public getter and setter methods generated for complex types, but also other useful methods, such as valued constructors, builder methods, hashCode, equals and toString methods can be implemented using XJC extensions." This post is about how to do this.

Our project uses XFire's WsGenTask Ant task to generate service interfaces, DTO classes and exceptions from WSDL file and the referenced XSD files. WsGenTask delegates the generation of DTO classes to JAXB's XJC compiler. However, these DTO classes generated by JAXB XJC's default are not particularly developer-friendly, in the following aspects:
  1. They have only one default constructor. This is quite inconvenient when you need to instantiate a DTO to hold some values:

    • You need to declare a local variable, which may otherwise be unnecessary.

    • You need to call the constructor to instantiate a new instance, then you need to invoke the setter methods for each property value you would like to it to hold.

    • To re-use the code and get rid of the local variable declaration, you need to create a factory class with one or more overloading create methods for each DTO class, which essentially are value-taking constructors moved to a factory class.

  2. They do not override the hashCode(), equals(Object) and toString() methods of the Object class. DTOs are value objects and no identity. Two instances holding exactly the same data should be considered interchangeable. Thus, overriding hashCode() and equals(Object) is essential for DTO classes. Moreover, not overriding toString() implementation makes it inconvenient in unit testing:

    • You cannot invoke assertEquals(Object, Object) directly. You have to rely on a static method to determine whether two objects are equal in values. And if the assertion fails, you need to invoke another static method to have a useful string representation of both the expected and actual objects.

  3. Default values are not honoured in the generated classes, that means you have to set the value explicitly even if you are using a default value in most cases.

  4. If you are not the owner of the schemas being used, the class and property names generated may not be following the Java's camel-case conventions.
  5. There is no setter method for collections. You need to invoke the getter method to retrieve the collection and invoke the addAll(Collection) method to add all elements of the prepared collection.

  6. If an element has a maxOccurs attribute value greater than one, the getter method generated is not using plural by default.

  7. Date, time and dateTime are generated as XMLGregorianCalendar, which requires constant conversion to and from the java.util.Date and java.util.Calendar values you use in your domain models.

Fortunately, XJC has an extension option that allows third-party extensions. A whole bunch of XJC plugins have been developed to iron out most of these isses in the open source community, and many of them are under the JAXB 2.0 Commons project hosted by java.net.

Many of the these plugins are very useful:
  1. The Value Constructor plugin generates a constructor that takes values for all properties besides the default no-argument constructor.

  2. If you have many properties in a DTO class, or some of the properties are optional, you can use the Fluent API plugin, which generates builder-styled methods, which essentially provides named-parameter constructor, which is not provided by Java.

  3. The jakarta-commons-lang plugin generates overriding hashCode(), equals(Object) and toString() methods using jakarta commons lang's HashCodeBuilder, EqualsBuilder and ToStringBuilder classes, which in turn uses reflection.

  4. The Default Value plugin honours the default values specified in the schemas.

  5. The CamelCase Always plugin generates class and property names following the camel-case convention.

  6. The Collection Setter Injection plugin generates setter methods for collections.


Unfortunately, at the time of this writing, XFire's WsGen does not pass parameters to JAXB's XJC, as tracked by this XFIRE-1038 JIRA. The way to get around it is to call the XJCTask Ant task after the WsGenTask call and overwrite all DTOs generated by WsGenTask.

Note that some of the plugins required JAXB 2.1 to work. If you intend to use JAXB 2.0 in runtime environment, it is fine: you can generate the classes using JAXB 2.1 with the target specified as "2.0" to avoid generating annotations introduced in JAXB 2.1.

To generate a plural form for collections, use a simple JAXB binding file with XJCTask.

If you would like to work with java.util.Date or java.util.Calendar instead of XMLGregorianCalendar, you can provide your own parseMethod and printMethod and specify them in your JAXB binding file used by XJCTask, as detailed by Sun's engineer Kohsuke's blog entry.

Follwing are extracted from the ant build file to illustrate how to generate developer-friendly DTO classes using JAXB:

<!-- This task will autogenerate the code from the XSD specification -->
<taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask" >
<classpath>
<pathelement path="${jaxb1-impl-2.1.3.jar}:${jaxb-api-2.1.3.jar}:${jaxb-impl-2.1.3.jar}:${jaxb-xjc-2.1.3.jar}" />
<pathelement path="${jaxb2-commons-commons-lang-plugin.jar}"/>
<pathelement path="${jaxb2-commons-value-constructor.jar}"/>
<pathelement path="${jaxb2-commons-fluent-api.jar}"/>
<pathelement path="${jaxb2-commons-default-value-plugin.jar}"/>
<pathelement path="${jaxb2-commons-collection-setter-injector.jar}"/>
<pathelement path="${component.classpath}" />
</classpath>
</taskdef>

<!-- This task will autogenerate the code from the WSDL specification -->
<taskdef name="wsgen" classname="org.codehaus.xfire.gen.WsGenTask" >
<classpath>
<pathelement path="${component.classpath}" />
</classpath>
</taskdef>

<!-- Auto generate classes based on the XSD definitions using JAXB bindings -->
<target name="xjc_gen">
<mkdir dir="${component.autogen_src}"/>
<delete>
<fileset dir="${component.autogen_src}"
excludes="**/service/**/*.java"/>
</delete>
<xjc destdir="${component.autogen_src}" target="2.0" extension="true">
<arg value="-Xcommons-lang"/>
<arg value="-Xvalue-constructor"/>
<arg value="-Xfluent-api"/>
<arg value="-Xcollection-setter-injector"/>
<arg value="-Xdefault-value"/>
<schema dir="${component.home}/src/conf/wsdl" includes="*.xsd"/>
<binding file="${component.home}/src/conf/wsdl/simple.xjb"/>
</xjc>
</target>

<!-- Auto generate interfaces and classes based on the WSDL definitions using JAXB bindings -->
<target name="wsdl_gen">
<mkdir dir="${component.autogen_src}"/>
<wsgen outputDirectory="${component.autogen_src}"
wsdl="${component.home}/src/conf/wsdl/service-foo.wsdl"
package="com.blogspot.ozgwei.service.foo"
overwrite="true"
binding="jaxb"
externalBindings="${component.home}/src/conf/wsdl/simple.xjb"
/>
<wsgen outputDirectory="${component.autogen_src}"
wsdl="${component.home}/src/conf/wsdl/service-bar.wsdl"
package="com.blogspot.ozgwei.service.bar"
overwrite="true"
binding="jaxb"
externalBindings="${component.home}/src/conf/wsdl/simple.xjb"
/>
</target>

<!-- Build all user, autogenerated and test code -->
<target name="compile" depends="wsdl_gen, xjc_gen">
...
</target>


The next is the content of the simple.xjb file for JAXB Binding, which use java.util.Calendar:

<!--
This enables the simple binding mode in JAXB.
See http://weblogs.java.net/blog/kohsuke/archive/2006/03/simple_and_bett.html
-->
<jaxb:bindings jaxb:version="2.0" jaxb:extensionBindingPrefixes="xjc"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<jaxb:globalBindings>
<xjc:simple/>
<jaxb:javaType name="java.util.Calendar" xmlType="xs:date"
parseMethod="javax.xml.bind.DatatypeConverter.parseDate"
printMethod="javax.xml.bind.DatatypeConverter.printDate"/>
<jaxb:javaType name="java.util.Calendar" xmlType="xs:time"
parseMethod="javax.xml.bind.DatatypeConverter.parseTime"
printMethod="javax.xml.bind.DatatypeConverter.printTime"/>
<jaxb:javaType name="java.util.Calendar" xmlType="xs:dateTime"
parseMethod="javax.xml.bind.DatatypeConverter.parseDateTime"
printMethod="javax.xml.bind.DatatypeConverter.printDateTime"/>
</jaxb:globalBindings>
</jaxb:bindings>


If you prefer to use java.util.Date instead of java.util.Calendar, define the following class and change the binding file accordingly:

package com.blogspot.ozgwei.jaxb

import java.util.Date;
import javax.xml.bind.DatatypeConverter;

public class DateConverter {

public static Date parseDate(String s) {
return DatatypeConverter.parseDate(s).getTime();
}

public static Date parseTime(String s) {
return DatatypeConverter.parseTime(s).getTime();
}

public static Date parseDateTime(String s) {
return DatatypeConverter.parseDateTime(s).getTime();
}

public static String printDate(Date dt) {
Calendar cal = new GregorianCalendar();
cal.setTime(dt);
return DatatypeConverter.printDate(cal);
}

public static String printTime(Date dt) {
Calendar cal = new GregorianCalendar();
cal.setTime(dt);
return DatatypeConverter.printTime(cal);
}

public static String printDateTime(Date dt) {
Calendar cal = new GregorianCalendar();
cal.setTime(dt);
return DatatypeConverter.printDateTime(cal);
}

}


The simple.xjb will be changed to:

<jaxb:bindings jaxb:version="2.0" jaxb:extensionBindingPrefixes="xjc"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<jaxb:globalBindings>
<xjc:simple/>
<jaxb:javaType name="java.util.Date" xmlType="xs:date"
parseMethod="com.blogspot.ozgwei.jaxb.DateConverter.parseDate"
printMethod="com.blogspot.ozgwei.jaxb.DateConverter.printDate"/>
<jaxb:javaType name="java.util.Date" xmlType="xs:time"
parseMethod="com.blogspot.ozgwei.jaxb.DateConverter.parseTime"
printMethod="com.blogspot.ozgwei.jaxb.DateConverter.printTime"/>
<jaxb:javaType name="java.util.Date" xmlType="xs:dateTime"
parseMethod="com.blogspot.ozgwei.jaxb.DateConverter.parseDateTime"
printMethod="com.blogspot.ozgwei.jaxb.DateConverter.printDateTime"/>
</jaxb:globalBindings>
</jaxb:bindings>