Mimic facelet layouts in grails

I wanted to mimic facelets <ui:insert /> and <ui:define /> tags in grails.I find facelets to be quite powerful because it allows to define a fragment in your template that can be redefined by the view, otherwise a default fragment is displayed.It can be useful for instance for a menu where you want all views to use a default menu and some use another menu.

In facelets, you would create a template file and add a <ui:insert /> statement for the menu, like this:

<ui:insert name="menu">
<ui:include src="../frags/menu.xhtml" />
</ui:insert>

Here the <ui:insert/> statement by default includes with the help of the <ui:include/>element a menu fragment (a partial page).

In your view you could if wanted redefine the menu with the <ui:define/> element, like this:
<ui:composition template="layout/template.xhtml">
<ui:define name="menu" />
</ui:composition>

Override default menu here

Grails template system is handled by sitemesh. To achieve the same goal, you can in your template file (layout/main.gsp for instance), add the following element for the menu :

<g:pageproperty name="page.menu" default="${render(template:'/frags/menu')}" />

It achieves the same purpose, actually instead of defining a page section like in facelets, it displays the calling page’s <content> element named menu if present (control is inverted but the result is the same).Otherwise, if the <content> element is not found, the menu fragment is rendered.The fragment page should be in our example created in the frags directory under the name _menu.gsp. In your view, you can therefore define the menu section of your template by declaring a content element.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="layout" content="main" />
<title>Show Book</title>
</head>
<body>
<content tag="menu">
<div>Override default menu here</div>
</content>
<!-- More content here -->
</body>
</html>

Seam usage in production

There ‘s an interesting thread on the Seam forum about Seam in “profesional use”. Performance and steep learning curve are often mentioned as drawbacks.

Seam heavily relies on proxy based components created by javassist. And javassist is known to be unperformant compared to cglib. This library might have been chosen due to politic reason at JBoss. Seam Managed Persistence Context (SMPC) is also seen as a culprit but i guess that like many other frameworks you have to understand what’s underneath the carpet, lazy loading in some use cases can really hit performance.

Scalability is not mentioned but i guess that since Seam is stateful it also can be an issue for large websites.

For the learning curve, it might be true if you don’t come from the JavaEE world or have never developed JSF applications. Seam still requires good knowledge of JSF 1.X and how it corrects it in many ways. The request lifecycle is also complex albeit powerful.Also other “lightweight” JSF based frameworks are quoted like makefaces.

Seam for me is both a IOC container specialized for web development and a web integration framework of Java EE (Ejb,Web beans), JBoss stack (jBPM, Drools, Richfaces, JSFUnit) and commonly used libraries (quartz,jfreechart, itext, javamail,etc.) It also addresses many commonly asked features (conversations, mail sending, page caching,etc.) I am not sure for the future of Seam. Seam 3 might be a complete rewrite due to support of JSF 2 and JSR-299 aka Java Contexts and Dependency Injection, but it is a comprehensive and efficient web framework with a decent IDE (JBoss tools).

Economic downturn and impact on javabloggers

I wanted to know if the economic crisis had an impact on blogging. I was curious because it seemed for me that the blogs that i usually follow had less activity . With the help of a groovy script and gchart, here’s the last 2 years monthly blog posts count (don’t know why there’s a high peak for July 07). It seems that, so far, java bloggers still post.

For the quality of the blog posts that’s another story but my blog is not a good example ;-)

The source :

JBoss resources

I recently discovered 2 good web sites that provide good JBoss knowledge :

  • Master the boss : especially with articles with jBPM/JBoss ESB integration, jBPM best practices and JBoss AS tuning (a little bit outdated by the way, but still a good resource).
  • Enterprise BPM blog : blog by a Redhat engineer involved in jBPM and WS-BPEL jBPM implementation. It has also links to other jBPM related sites.

Some Maven tips

First post of the year, here are some Maven tips you might find useful (or obvious for experienced users):

  • How to version commercial libraries in your SCM and use them as dependency ?

In case you don’t have your own central repository and you’d like to version your libraries in your SCM server, you can declare in your pom a repository like this :

<repository>
  <id>sipphonyrepo</id>
  <url>file:///${basedir}/../repository</url>
</repository>

The ‘repository’ directory should be versioned in your scm server but it also means that it should be checked out with your project. Also like any other repository, the dependencies will be copied in your local repository.

*How to just copy files ?

It might be useful on a development machine to copy files while installing an artifact, for instance you might want to copy a JBoss datasource file to a JBoss profile to make sure it’s deployed. For this you can use the Maven resource plugins. For instance the following plugin statement will copy the datasource file to your JBoss server’s default profile deployment directory if JBOSS_HOME environment library is defined (on the development machine) :
<profile>
<id>jboss.deploy</id>
<activation>
<property>
<name>env.JBOSS_HOME</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<artifactid>maven-resources-plugin</artifactid>
<version>2.3</version>
<executions>
<execution>
<id>copy-ds</id>
<goals>
<goal>copy-resources</goal>
</goals>
<phase>install</phase>
<configuration>
<outputdirectory>${env.JBOSS_HOME}/server/default/deploy</outputdirectory>
<resources>
<resource>
<directory>${basedir}</directory>
<includes>
<include>mysql-ds.xml</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
  • How to perform complex build build logic ?

One solution would be to use profiles for that like in the above example. But it can quickly become cumbersome and limited. So a good option is to use Ant Maven plugin with ant-contribs dependency for control statements and loops or even better the groovy GMaven plugin (avoiding XML verbosity).Profiles have still the benefit of clearly identifying an intent in your build. The following command will list all profiles:

mvn help:all-profiles

If build logic can be extracted and used in different contexts, it’s time to create a plugin. It’s quite simple.

  • How to create an artifact of a zip or tar ?

One obvious solution is to use maven assembly plugin but if you need to add some custom logic during packaging, you could just create the zip or tar file with Ant maven plugin or groovy GMaven plugin and gant during the package phase. Then attach the file to your project with Maven build helper plugin and its attach-artifact goal to install it in your repository during the install phase. Once installed in your local repository, the zip or tar file can be become a dependency, just use the proper type in the dependency declaration.

<type>zip</type>
  • How to create a full delivery layout with multiple archetype ?

My advice for creating a comprehensive delivery directory structure would be to use a dedicated module, take advantage of ant,assembly and resource plugins for that. Struts2 has such a module : see the assembly module’s pom

Spring maintenant payant

Oui la nouvelle du week-end ou plutot de fin de semaine sur le changement de licence de Spring me reste en travers de la gorge, même si j’en comprends les raisons.

Mais d’un coup je me sens coupable d’avoir poussé depuis 2004 à l’utilisation de Spring sur plusieurs projets et d’en avoir été le défenseur auprès de certains collègues réticents sur les principes d’injection de dépendances, de conteneur léger et même d’AOP. Sur mes 2 derniers projets, j’ai même introduit Spring Security (anciennement ACEGI) et utilisé Spring MVC pour une petite application interne chez mon employeur précédent. Et oui, le changement de licence s’applique aussi à tous ces projets.Cela me fait maintenant me re-questionner sur l’utilisation de ce framework.

D’abord pourquoi Spring ? Logiquement après avoir lu les livres de Rod Johnson “J2EE design and development” et “J2EE Development without EJB” son utilisation semblait être une vrai alternatives aux Ejb 2.x pour les raisons suivantes :

  • des objets et services métiers n’implémentant aucune interface technique (juste des POJO).
  • l’injection de dépendances favorisant le couplage faible entre les objets.
  • les tests unitaires sans déployer dans le conteneur EJB accélérant ainsi les phases de test.
  • la rapidité de démarrage du conteneur Spring pemettant de l’utiliser en dehors d’un serveur application.
    Mais Spring est aussi utilisé maintenant pour toutes ses fonctionnalités qui facilitent le développement d’application JavaEE :
  • son intercepteurs transactionnels et son annotation @Transactional
  • l’accès aux services des serveurs d’application par simple déclaration (j2ee:jndi-lookup)
  • la création de proxy sur des Ejb (2.1, 3.0), Web-Services (JAX-RPC et JAXWS) .
    En fait, j’ai en fait toujours été très satisfait de Spring Core et impressionné par sa stabilité et son excellente documentation tout cela en opensource et gratuit. Les applications développées avec étaient même plus portables que les traditionnelles applications J2EE. Mais la lune de miel a une fin et je pense maintenant que je vais devoir m’intéresser aux alternatives, car je vois mal certains clients payer pour une librairie (cela changera peut-être pour avec Spring dm Server).

    Les alternatives

Pour moi la + évidente :

  • JavaEE 5 et les EJB 3
    Et oui avec des conteneurs d’EJB en mode embedded pouvant être utilisés pour les tests et démarrant en quelques lignes de codes ( voir par exemple OpenEJB de la fondation Apache ou encore JBoss embedded ). De + cette solution a l’immense mérite d’être standard.Maintenant techniquement, le mécanisme d’interception d’EJB 3 n’est pas aussi riche que celui proposé par Spring et son support d’AspectJ. Le mécanisme ne permet d’injecter uniquement des Ejbs ou des ressources JNDI. Mais au moins les tests sans déploiement sont possibles, le code simplifié et épuré. De +, Ejb 3.1 apportent aussi son lot de nouveautés comme l’annotation @Singleton ou la non-obligation de créer une interface métier.

  • Guice

Peut-être un peu jeune et n’est qu’un “IOC container” mais pourquoi pas pour une utilisation pour des applications standalone.

Some common JSF pitfalls

Well at least here’ s a non exhaustive list of common jsf pitfalls, i felt into (some are variants of others) :

  • Using a converter in a SelectOneMenu or SelectManyList components, be careful of type being applied. See http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=82&t=003594. Using an array instead of typed collection for the component input values ( still not sure why, have investigated too much on it, so i won’t extend on it)!
  • Declare a resource bundle in the page ( most of the time bundles are declared in a template page) with the loadbundle element instead of declaring it the faces-config.xml file . If done so, requiredMessage or converterMessage attibutes that can be applied to many UIInput components won’t work (i.e the message won’t be found).
  • With a commandLink inside dataTables with a bean of request scope actions are not executed. At least it happened to me with JSF RI 1.2_07 and is due to the fact that the id of the dataTable component is changed between the component tree creation (restore view phase) and the render response phase ( Update 09/21/2008 : See more explanations on this in the comment section by Dan Allen himself, author of “Seam in Action” ). When submitted on a post back request, the actions event are not queues (passed as hidden fields). It’s well detailled here http://typo.ars-subtilior.com/articles/2007/02/07/jsf-datatable-and-commandlink. As a workaround, i used the tomahawk savestate component for the elements of the datatable. This component stores the state of objects passed as value expression in the component tree (having a scope that spans between the inital request restore view and post back render response phase) . Seam has a page scope for that.
  • Validation errors when using a converter in selectOne* components and not overriding the equals() method for the type of object in the list. More explanation here : http://www.crazysquirrel.com/computing/java/jsf/converter-validation-error.jspx
  • Saving state on client side with hidden fields and having conversion or validation issues with a backing bean of request scope: state is lost. For instance, you have an inputHidden component in your form and for a reason or another a form’s field has conversion or validation issues. The backing bean of request scope is not updated for the postback request. The bean used to display the response is new and the inputHidden‘s field value is reset. Once again this shows a lack of page context for state that needs to be kept between the initial request and the postback request.
  • Programmatic submission of a web form in javascript through form’s submit method won’t work because the actionlistener is registred on a commandButton and when the form is submitted, the submit button parameter is not passed in the request. The button’s action event is not put in the event queue. A workaround is to programmatically click on the form’s command button.