Second milestone of spring-test-mvc

A second milestone of the Spring MVC Test project, version 1.0.0.M2 is now available through the SpringSource Artifactory repository http://repo.springsource.org/milestone.

There is much that’s new in this release. On the server side:

  • Support for servlet filters (see FilterTests.java); and in turn basic support for Spring Security (see SpringSecurityTests.java). Thanks to Rob Winch!
  • Ability to define default request properties and expectations to re-use across every performed request (see JsonPathAssertionTests.java)
  • An extension point for adding request-building methods in addition to the ones that are built-in (see SecurityRequestPostProcessors.java)
  • Support for “input” flash attributes
  • Upgrade to json-path 0.8.1
  • Lots of bug fixes, general improvements
  • Completed Javadoc

On the client side — which is used for tests that involve direct or indirect use of the  RestTemplate — we have a greatly expanded the selection of options for request matching (see the match package) as well as the options for response creation (see the response creators), lots of general improvements, and completed Javadoc.

In the very near future, the project source code will be replicated in the master branch of the Spring Framework and will be released with Spring 3.2 RC1 as part of the spring-test module, which will become its permanent home. In the mean time the spring-test-mvc project on Github will continue to exist and provide support for applications built on Spring 3.1.x.

I hope to see some of you at SpringOne, in less than a month, where I’ll be talking about this project in more detail co-presenting with Sam Brannen on  “Testing Web Applications with Spring 3.2″.

Posted in Spring Framework, Spring MVC | 1 Comment

Early Milestone of Spring Test MVC

A milestone release (version 1.0.0.M1) of the Spring Test MVC project is now available through the SpringSource artifactory repository. If you’ve been using the project the http://repo.springsource.org/libs-snapshot repository, you can also use it for milestones. Alternatively you can use the http://repo.springsource.org/libs-milestone repository. For more details see the SpringSource Repository FAQ.

The project has become quite popular already and there have been many questions surrounding its release date. As mentioned on the project home page the plan is to fold it back into the spring-test module of the Spring Framework in Spring 3.2. In the mean time, milestone releases will continue to be released in parallel with milestone releases of Spring 3.2.

One of the test-related features in Spring 3.2 that is relevant to Spring Test MVC is Support for Web Applications in the TestContext framework. That will become available in Spring 3.2 M2 allowing Spring Test MVC to build on it.

Thanks to everyone using the project, providing comments, as well as contributions. Keep them coming!

Posted in Spring MVC | 7 Comments

SpringOne 2GX

Below are links to my presentations at SpringOne 2GX 2011. Each presentation contain links to resources and demo code.

A walk-through the programming model and other changes in Spring MVC 3.1. Designed to be easy to follow without a speaker:

Spring MVC 3.1 Update

An up-to-date view on Spring config including singificant Java config updates (co-presented with Chris Beams):

Spring 3.1 Configuration Enhancements

Spring 3.1 TestContext framework updates and a new @MVC Test framework (co-presented with Sam Brannen):

Spring 3.1 and Spring MVC Testing Support

Posted in Uncategorized | 4 Comments

Spring 3.1 Talk at JAX Free Preview Night

I’ll be giving a talk at JAX Preview Night. Registrations are free. The actual JAX conference will take place on April 11-13 in London.

JAX.

Posted in Uncategorized | Leave a comment

javax.validation Package Dependency Diagram

I’ve looked through JSR-303 before but now starting to read in more detail. Don’t know what this is due to yet but I am a bit surprised to see the tangles in the package diagrams (courtesy of Structure 101).

Validation API:


javax.validation Package Dependencies Diagram

Hibernate Validator:


Hibernate Validator Package Dependencies Diagram

Will know more once I understand all the relationships.

Posted in Hibernate | Leave a comment

Bean Validation Messages in JSF 2

JSF 2 introduced support for standard JSR-303 Bean Validation. One of the surprising bits was the default error messages.

Suppose I added an annotation to one of my form beans as follows:

public class Booking {

    @NotEmpty
    private String creditCardName;

}

and then I bind it to a form input field:


<h:messages />

<h:inputText label="Credit Card Name" 
            value="#{booking.creditCardName}"/>
  

The resulting error message I get is: “may not be empty”. Huh? What may not me empty? :)

This makes no sense when shown as a global message at the top of the page. You get a sequence like “may not by empty, may not be null, must be in the future”. This also makes no sense when shown as a field specific message either: “may not be empty” is a partial sentence. I recall being surprised by this initially and that I’d have to come back to it eventually.

So I did and here is what I found out. To start off the above messages are defined by the Bean Validation provider (Hibernate Validator in this case) in a file called ValidationMessages.properties. When the JSF BeanValidator invokes Bean Validation and then formats the messages, it holds two pieces of data — one is the constraint message (e.g. “may not be empty”) and the second is the field label (“Credit Card Name”). To format the message the BeanValidator uses the pattern “{0}”, which practically ignores the field label.

Mind you that I had to find this out by debugging. And it’s what most developers would have to do. It turns out the spec has something to say about this. Here is a quote:

To encourage use of the Bean Validation message facility, the default message format string for the BeanValidator
message key must be a single placeholder, as shown here:

javax.faces.validator.BeanValidator.MESSAGE={0}

Putting the Bean Validation message resolution in full control of producing the displayed message is the recommended approach. However, to allow the developer to align the messages generated by the BeanValidator with existing JSF 1.2 validators, the developer may choose to override this message key in an application resource bundle and reference the component label, which replaces the second numbered placeholder (i.e., {1}).

javax.faces.validator.BeanValidator.MESSAGE={1}: {0}

If I understand correctly, the intent behind all this is to encourage use of Bean Validation facilities to control messages. Seems like a fair idea but one that I don’t get on multiple levels.

  1. How would the Bean Validation provider know what is an appropriate label for a given Java field? This is the domain of JSF and that’s why I have a “label” attribute on my <inputText> above.
  2. The default behavior you get out of the box is one that I can’t imagine anyone would want. So everyone has to do extra work to get JSF and Bean Validation to produce messages based on JSF component labels.
  3. This changes the behavior from JSF 1.2 for an unknown benefit.

Well, maybe there is something in the Bean Validation spec that can address this. I haven’t found this yet but logically it seems to be that labels are defined in JSF components and the JSF integration with Bean Validation should make use of that.

In the mean time to correct this you’ll need to create a resource bundle, overwrite the message pattern the BeanValidator uses, and then register your resource bundle in faces-config.xml.

For example I add ApplicationMessages.properties to my classpath with this content:

javax.faces.validator.BeanValidator.MESSAGE={1} {0}

Then I register it in faces-config.xml as follows:


<?xml version='1.0' encoding='UTF-8'?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="

http://java.sun.com/xml/ns/javaee


http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"

        version="2.0">

	<application>
		<message-bundle>ApplicationMessages</message-bundle>
	</application>
	    
</faces-config>

At last I get: “Credit card name may not be empty”! Simple solution but a long winded path to get to it.

Posted in JSF | 5 Comments

Shared Nothing Event-Loop Concurrency

Reading the above quote in a blog post about CommonJS/JSGI: The Emerging JavaScript Application Platform peeked my interest. What were they talking about? Digging around I found this really interesting talk by Ryan Dahl on event-loop concurrency.

The approach resonates with me for two reasons. One, as a Java developer I’ve seen a lot of improvements related to concurrency in the last few years. Yet fundamentally concurrency remains a significant issue. It’s neither simple to make programs safe, not is it simple to test for such conditions. Two, I once worked on a high-performing trading application that was built from the start as an event-driven system where services did not return values but posted messages on an internal message bus.

It’s interesting that JavaScript, which is now building up server-side support can approach concurrency differently.

Posted in JavaScript | Leave a comment

“Uses” Directive In OSGi

Over the last 2 weeks I had a chance to teach the 2-day dm Server course 3 consecutive times. One of the topics that inevitably generates a lot of interest is the “uses” directive in OSGi, which is neither easy to grasp nor to explain.

My own first encounter with the “uses” directive was in the form of the mysterious “uses conflict” messages when trying to deploy bundles into an OSGi environment. I say mysterious because they mean nothing to the uninitiated and also because they require a fair amount of research. At the end I provide some links for a more complete understanding. In the mean time I’ll offer my own plain word explanation.

The ability to run multiple versions of the same bundle (or jar) in OSGi is well-known. For example I am a bundle and I need Hibernate 3.2.6.ga. You’re a bundle and you need Hibernate 3.5. We can run side by side in OSGi because the OSGi runtime creates separate classloaders for your bundle and for my bundle, which makes it possible to use different versions of Hibernate.

The problems starts if I decide to use packages exported by you. Why is that a problem? If a class exported by you returns a Hibernate type, I may try to use it, in which case I’ll probably run into problems like LinkageError because you’re essentially using a different version of Hibernate.

That’s the problem. The solution involves the OSGi “uses” directive, which lists packages used in an exported package. The OSGi resolver takes that information and works out if problems like the one above are likely to occur. If so it produces the “uses conflict” message well ahead of runtime exceptions such as LinkageError, ClassCastException, and others.

To understand the solution consider the fact that the descibed issue occurs only if I come into “contact” with a Hibernate type passed to me through one of your exported classes. If you use Hibernate internally and never expose it in your exported packages then the issue would never occur.

If you accept the above problem and solution one more thing that leads to questions is how the uses directive is maintanted. Clearly it’s a fair amount of work figuring out everything your exported packages use. That’s a job for tools like bundlor and bnd.

For more details I highly recommend looking at:

  • The OSGi specification, which has very readable definitions and examples in sections 3.5.5 (Export Package) and 3.6.4 (Package Constraints).
  • This blog by Glyn Normington that explains the basic problem (note the comments section where he suggests that either bundles should use matching versions or that a bundle is refactored not to export any of the types causing the conflict).
  • This follow-up blog by Rob Harrop that provides a realistic example involving Spring ORM and two versions of EclipseLink. It also provides a step by step approach to debugging such issues in the OSGi console, which is key to understanding the messages then produced in dm Server. Lastly there is an interesting variation on how this problem can occur based on deployment order.
Posted in OSGi | Leave a comment

Fetch Profiles In Hibernate 3.5

A beta version of Hibernate 3.5 was announced last week. The release will contain initial support for a feature called fetch profiles that is really useful for retrieving different footprints of the same entity. You can see the actual JIRA ticket HHH-3414 for more details about the feature.

Why is this useful? Let’s assume you have an Person entity with 3 associations – addresses, jobs, and hobbies. Common Hibernate wisdom advises us to keep those associations with default lazy loading settings in the mappings and override them via fetch joins at runtime for each use case. This is simple enough but let’s move on. Suppose your PersonDAO has 5 queries for finding persons by first name, last name, email, age, or some combination of the above.

This is where it gets tricky. If your application fires too many queries because lazy loading is not fetching enough data up front then you’d probably consider an optimization by providing alternative finder methods that fetch the required associated entities. So you’d have findByLastName, findByLastNameWithAddresses, findByLastNameWithJobsAndHobbies, and so on. It gets pretty confusing and the full combination is 5 finders x 10 combinations (4 + 3 + 2 + 1) = 50. And this is only an example with 3 associations without considering property paths with a depth greater than 2.

What can be even more concerning in such scenarios is that in a large application a developer that runs into a lazy loading exception or realizes that some optimization is needed would probably go back and add a ‘fetch’ join potentially affecting other scenarios and bringing back more data than is needed. There is nothing in the DAO design that would make the developer consider the performance impact because things would still work.

The fetch profiles will allow a DAO to manage all this more elegantly by accepting a parameter that represents the desired fetch profile. It would also encourage the developer to consider the available profiles without running the risk of affecting the performance of other use cases adversely.

Posted in Hibernate | 1 Comment

GSP and JSP

The question why Grails has GSP when there is JSP is a natural one. Here are a few substantial differences:

  1. A GSP allows the same ${…} expressions as in a Groovy GString. JSP EL expressions are restricted to object navigation, which is generally a good idea but can also make it difficult to access anything that isn’t a getter (e.g. String length()). JSTL functions provide some help but the more general case requires creating static helper methods, registering them through a taglib descriptor, adding a taglib declaration, and finally using the function.
  2. Using Groovy in logical and iterative tags comes with major perks such as the safe navigation operator: ${customer.phones?.size()} or the Elvis operator: ${totalCount ?: 10}.
  3. The ability to invoke Grails dynamic tags as methods makes it easier to produce well-formed markup:
    
    <!-- With a regular tag -->
    <a href="<g:createLink action="list" />">A dynamic link</a>
    
    <!-- As a method call -->
    <a href="${createLink(action:'list')}">A dynamic link</a>
    
    
  4. GSP provides a much simpler mechanism for creating and testing custom tag libraries in Groovy that does not require tld files and taglib declarations and of course uses Groovy. Here is a sample test case for a Grails tag library:
    import grails.test.*
    class CustomerTagLibTests extends TagLibUnitTestCase {
      void testRepeat() {
        tagLib.repeat(times: '2') {
          'output<br/>'
        }
        assertEquals 'output<br/>output<br/>', tagLib.out.toString()
      }
    }
    
  5. The Grails paginate tag. It is such a common need for web applications. In comparison to the Displaytag library I think the Grails paginate tag is more lightweight and more usable.
Posted in Grails | 4 Comments