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

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.

Comments

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.

Comments

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.

Comments (4)

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.

Comments

“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.

Comments

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.

Comments

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.

Comments (2)

WebLogic Server Tools For Eclipse

I just spent an afternoon putting too much trust in the WebLogic sever tools for Eclipse. My modest goal was to modify a JSP and see the change without me having to do anything about it. It’s just a simple file copy after all.

From what I could see there are two ways to deploy my Eclipse web project. One involves an auto-generated EAR and the other an auto-generated WAR. With either option any time I changed a JSP the auto publishing feature kicked in to rebuild the auto-generated artifact (including compilation) and to re-publish to the server. For any project of a decent size (the most common kind out there) this is completely useless, not to mention unnecessary. Furthermore the republished EAR somehow managed to consistently exhaust the connection pool.

So the only thing the plugin seems to be good for is to start and stop Weblogic from within Eclipse and possibly in debug mode. Both of these I can do just as easily and more reliably from the command line. So why isn’t there an option for deploying my web project in exploded form so that a JSP change is a simple file copy? Wouldn’t that be the simplest default?

For all the “high-end” features an application server like WebLogic provides it’s amazing to me how long countless developers have to wait for each time they make a simple JSP change.

Comments

Debugging With Spring JavaScript

One thing Spring JavaScript does really well is enable rich client-side behavior in your application using best practices and without the need to learn JavaScript in-depth. This is great news but sooner or later you’ll run into a situation where you’ll wonder why a form is not submitting via Ajax, or perhaps is not submitting at all. It may sound scary but it’s actually not so hard to figure out your problem.

Use the Firebug add-on for Firefox. Click on the Net tab and see if any requests (either full refreshes or Ajax requests) are going out at all. If so check use the Net tab to see the actual response returned from the server. In most cases the above information is enough of a clue. On occasion though you’ll need to break out the debugger.

Using Firebug’s Script tab find the code you need, set a breakpoint, and re-execute the test or refresh the page. It’s quite easy to start stepping through although soon you’ll step into minified JavaScript. To get around that one option is modify your JavaScript includes. For example change dojo.js to dojo.js.uncompressed.js and Spring-Dojo.js to Spring-Dojo.js.uncompressed.js.

A second and more convenient option is to extract the uncompressed versions of the files (dojo.js.uncompressed.js and Spring-Dojo.js.uncompressed.js) from the Spring JavaScript jar, and save them under the root of your web application so that they become accessible as /dojo/dojo.js and /spring/Spring-Dojo.js respectively. After you do that debugging will get much easier because you’ll no longer have minified JavaScript. If using svn set svn:ignore on these directories and you’ll never have to worry about it again for your local environment.

To understand why this works consider the fact that Spring JavaScript bundles JavaScript files in a jar and serves them from the classpath with its ResourceServlet servlet translating the URL it gets to a package location. If you however place files on the same path under the root of your web application, those files will take precedence thus allowing you to shadow resources normally served from the classpath.

Comments

« Previous entries Next Page » Next Page »