Tuesday, April 24, 2012

Saving on the fly generated PDF to file or database (Seam 2.2 application in JBoss AS 5.1)

With Seam, you can create a pdf file on the fly using only xhtml pages, but if you want to get the PDF file’s binary data, that is much harder task. The basic problem, that this function was not designed to provide the binary data, rather than just generate the PDF file using JSF custom tags. You can read the solution in a lot of blogs and forums: just create a mock FacesContext, use that for render the page, then extract the binary data. I have tried the solutions described in various places, but for JBoss AS 5.1 and Seam 2.2.0 GA they didn’t worked. The main problem was to create the mock FacesContext, because you have to have the javax.faces.application.Application and javax.faces.render.RenderKitFactory instances which I had no luck to get at the time of the creation of the mock FacesContext. But by implementing a servlet context listener, I was able to capture both values. You need to register the DocumentServlet and the custom servlet context listener into the web.xml, create the /simple.xhtml page (see later) and put the xhtml code in paragraph #3 into an other page (the menu, for example). The other classes should be put into the ejb module of your application, into the org.example.pdf package. Let's see the steps in detail:

1.Servlet Context Listener and Document Servlet registration in web.xml

In order the PDF generation on the fly to be able to work, you must add the followings servlet mapping to the web.xml. The servlet context listener is used to capture the javax.faces.application.Application and javax.faces.render.RenderKitFactory instances when the servlet context initialized.
<servlet>
    <servlet-name>Document Store Servlet</servlet-name>
    <servlet-class>org.jboss.seam.document.DocumentStoreServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>Document Store Servlet</servlet-name>
    <url-pattern>*.pdf</url-pattern>
</servlet-mapping>

  <listener>
    <listener-class>
        org.example.pdf.MockServletContextListener
    </listener-class>
  </listener>

2. Page that generates PDF

You must create a an xhtml page ("/simple.xhtml"), to test the export function:
<p:document xmlns:p="http://jboss.com/products/seam/pdf">                                                      
    <p:chapter>Hello PDF!</p:chapter>
</p:document>

3. Testing xhtml code

In order to test the PDF export function, the following link could be placed somewhere (e.g,: into the menu). This will call the mockPDFFileSaver’s savePDF(fileName, viewName) method, which simply generated the pdf then saves the results into the given file. This example will save the pdf into "d:\simple.pdf"
<s:link 
       includePageParams="false" 
       propagation="none" 
       value="Simple PDF test" 
       action="#{mockPDFFileSaver.
         savePDF('d:\\simple.pdf','/simple.xhtml')}">
</s:link>

4.Servlet Context Listener

The listener can capture the „Application” and „Render Kit Factory” instances. It then saves into the Seam component „factoryData”. Lifecycle.beginCall() initializes Seam.
package org.example.pdf;

import javax.faces.FactoryFinder;
import javax.faces.application.Application;
import javax.faces.application.ApplicationFactory;
import javax.faces.render.RenderKitFactory;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.jboss.seam.Component;
import org.jboss.seam.contexts.Lifecycle;

/**
 * ServletContextListener implementation to capture the JSF Application and
 * renderKitFactory. Should be registered into web.xml to work
 * 
 * @author anemeth
 * 
 */
public class MockServletContextListener implements ServletContextListener {

 public void contextDestroyed(ServletContextEvent event) {
 }

 public void contextInitialized(ServletContextEvent event) {

  Lifecycle.beginCall();

  Application application = ((ApplicationFactory) FactoryFinder
    .getFactory(FactoryFinder.APPLICATION_FACTORY)).getApplication();

  RenderKitFactory renderKitFactory = (RenderKitFactory) FactoryFinder
    .getFactory(FactoryFinder.RENDER_KIT_FACTORY);

  FactoryData factoryData = (FactoryData) Component.getInstance("factoryData", true);
  factoryData.setApplication(application);
  factoryData.setRenderKitFactory(renderKitFactory);

 }

}

5. Mock Servlet Context

The MockServletContext from Seam 2.2 was modified in order to work under JBoss AS 5.1
package org.example.pdf;

import javax.faces.FactoryFinder;
import javax.faces.application.Application;
import javax.faces.application.ApplicationFactory;
import javax.faces.render.RenderKitFactory;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.jboss.seam.Component;
import org.jboss.seam.contexts.Lifecycle;

/**
 * ServletContextListener implementation to capture the JSF Application and
 * renderKitFactory. Should be registered into web.xml to work
 * 
 * @author anemeth
 * 
 */
public class MockServletContextListener implements ServletContextListener {

 public void contextDestroyed(ServletContextEvent event) {
 }

 public void contextInitialized(ServletContextEvent event) {

  Lifecycle.beginCall();

  Application application = ((ApplicationFactory) FactoryFinder
    .getFactory(FactoryFinder.APPLICATION_FACTORY)).getApplication();

  RenderKitFactory renderKitFactory = (RenderKitFactory) FactoryFinder
    .getFactory(FactoryFinder.RENDER_KIT_FACTORY);

  FactoryData factoryData = (FactoryData) Component.getInstance("factoryData", true);
  factoryData.setApplication(application);
  factoryData.setRenderKitFactory(renderKitFactory);

 }

}

6. FactoryData

This is a simple Seam component for holding the „javax.faces.application.Application” and „javax.faces.render.RenderKitFactory”
package org.example.pdf;

import javax.faces.application.Application;
import javax.faces.render.RenderKitFactory;

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

/**
 * Class for holding the JSF "Application" instance and the renderKitFactory.
 * @author anemeth
 *
 */
@Name("factoryData")
@Scope(ScopeType.APPLICATION)
public class FactoryData {
 
 private Application application;

 private RenderKitFactory renderKitFactory;
 
 /**
  * @return the application
  */
 public Application getApplication() {
  return this.application;
 }

 /**
  * @return the renderKitFactory
  */
 public RenderKitFactory getRenderKitFactory() {
  return this.renderKitFactory;
 }

 /**
  * @param application
  *            the application to set
  */
 public void setApplication(Application application) {
  this.application = application;
 }

 /**
  * @param renderKitFactory
  *            the renderKitFactory to set
  */
 public void setRenderKitFactory(RenderKitFactory renderKitFactory) {
  this.renderKitFactory = renderKitFactory;
 }

 /**
  * @see java.lang.Object#toString()
  */
 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("FactoryData [application=");
  builder.append(this.application);
  builder.append(", renderKitFactory=");
  builder.append(this.renderKitFactory);
  builder.append("]");
  return builder.toString();
 }
}

7. MockPDFFileSaver

This is a simple Seam component to demonstrate the PDF export function
package org.example.pdf;

import java.io.FileOutputStream;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;

@Name("mockPDFFileSaver")
public class MockPDFFileSaver {

 @In(create = true)
 PdfExporter pdfExporter;

 /**
  * Saves the PDF generated by the pageName to the file denoted by the
  * fileName
  * 
  * @param fileName
  *            the file name
  * @param pageName
  *            the page name
  */
 public void savePDF(String fileName, String pageName) {
  byte[] pdfBytes = pdfExporter.pdfExport(pageName);
  try {
   FileOutputStream fos = new FileOutputStream(fileName);

   fos.write(pdfBytes);

   fos.close();
  } catch (Exception e) {

   e.printStackTrace();
  }
 }

}

8. PDFExporter

The pdf export functionality is implemented in this Seam component. This works by rendering the given view into a mock context. The DocumentStore then contains the rendered pdf. The real question is what the id of the generated pdf. The DocumentStrore is a Conversation scoped component so basically the Id will be started from 1 when a new conversation starts. But for sure, the Id can be queried, in the case more document is generated per conversation.
package org.example.pdf;

import java.io.ByteArrayOutputStream;

import org.jboss.seam.annotations.Name;
import org.jboss.seam.document.DocumentData;
import org.jboss.seam.document.DocumentStore;
import org.jboss.seam.faces.Renderer;

@Name("pdfExporter")
public class PdfExporter {
 
 /**
  * returns the byte array of the PDF file generated using the page xhtml 
  * @param page the page name of the xhtml for the pdf
  * @return the byte array containing the PDF file data
  */
 public byte[] pdfExport(String page) {

  byte[] pdfBytes = null;

  EmptyFacesContext emptyFacesContext = null;

  try {

   emptyFacesContext = new EmptyFacesContext();

   try {

    Renderer renderer = Renderer.instance();
    renderer.render(page);
    
    DocumentStore store = DocumentStore.instance();

    String nextId = store.newId();
    long docId = Long.parseLong(nextId) - 1;

    DocumentData data = store.getDocumentData("" + docId);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    data.writeDataToStream(baos);

    pdfBytes = baos.toByteArray();

   } catch (Exception e) {
    e.printStackTrace();
   }
  } catch (Exception e) {
   e.printStackTrace();

  } finally {
   emptyFacesContext.restore();
  }

  return pdfBytes;
 }

}

Friday, April 6, 2012

Localization Tool for Seam 2 applications

Internationalization and Localization in Seam applications

Seam uses the JSF's resource bundle approach to localization. Resource bundles are property files usually in the WEB-INF/classes folder. JSF can determine the locale using the followings (from Seam documentation):

  • If there is a locale associated with the HTTP request (the browser locale), and that locale is in the list of supported locales from faces-config.xml, use that locale for the rest of the session.
  • Otherwise, if a default locale was specified in the faces-config.xml, use that locale for the rest of the session.
  • Otherwise, use the default locale of the server.


To change the locale manually you should place some similar code into your application (e.g.: in the menu bar):
<h:selectOneMenu value="#{localeSelector.language}" 
    onchange="submit()">
    <f:selectItem itemLabel="#{messages.menu_language_en}" 
        itemValue="en"/>
    <f:selectItem itemLabel="#{messages.menu_language_de}" 
        itemValue="de"/>
    <f:selectItem itemLabel="#{messages.menu_language_hu}" 
        itemValue="hu"/>
</h:selectOneMenu>

In the above example three languages used: english (en), german (de) and hungarian (hu). The labels for the  selection list are also coming from the resource bundle, so they are displayed in the selected language. In the english resource bundle this looks like this way:


menu_language_de=German
menu_language_en=English
menu_language_hu=Hungarian

while in the german resource bundle:


menu_language_de=Deutsch
menu_language_en=English
menu_language_hu=Ungarisch

Seam will use the resource bundle of choice.

Enabling the localization in a Seam application


Modify the WEB-INF/components.xml to include the following:


<!-- Remember the locale selected -->
<international:locale-selector cookie-enabled="true"/>


where international is defined as

xmlns:international="http://jboss.com/products/seam/international"

For more information on internationalization please see Seam documentation: http://docs.jboss.com/seam/latest/reference/en-US/html/i18n.html


Pratical Localization

Let's suppose you have a Seam application developed in English language, and you have to add new languages. There could be String values in the Java code and in the xhtml pages. This tool deals only with the String literals in the xhtml pages. Every String which contains at least one letter (outside the EL expressions) are put into the resource bundle property files "messages_XX.properties". At the same time the tool changes the String literals in the xhtml pages to EL expression.

For example a h:commandButton without localization looks this way:

<h:commandButton action="#{providerHome.persist}" 
id="save" rendered="#{!providerHome.managed}" 
value="Create"/>

After the tool processed the xhtml code, the above excrept looks like this:

<h:commandButton action="#{providerHome.persist}" 
id="save" rendered="#{!providerHome.managed}" 
value="#{messages.provider_commandButton_Create}"
/>
You can see that the key for the "Create" String literal from the command button is:
provider_commandButton_Create. The first part "provider" is the name of the xhtml file without extension. The second part is the name of the JSF tag without namespace ("commandButton"), the last part is the String literal converted into a format suitable for being a key ("Create"). The non letter characters are converted into underscore. (Minus sign is not usable, because it is evaluated by the EL engine).

The provider_commandButton_Create is added to the messages_en.properties:
provider_commandButton_Create=Create
and for example the messages_de properties file:
provider_commandButton_Create=Erstellen
This kind of naming convention is applied to String literals inside value attribute of JSF tags. When the literal is a text node in the xhtml file, the middle part will be "TEXT":

<s:decorate id="nameField" template="layout/edit.xhtml">
     <ui:define name="label">#{messages.provider_TEXT_Name}
     </ui:define>
     <h:inputtext id="name" required="true" value="#{providerHome.instance.name}">
</h:inputtext></s:decorate>

Localizing date/time formats

The localization would not be complete without date formats. For example in hungary the following format is used: 2012-04-05 12:33:17 , while the traditional german format would be: 05-04-2012 12:33:17. The tool inserts the following key to the resource bundle property files: date_time_format. This will be used in 

<h:outputtext style="align: center;" value="#{user.registrationDate}">
    <f:convertdatetime pattern="#{messages.date_time_format}" timezone="CET">
</f:convertdatetime></h:outputtext>


Localization Workflow

  1. Develop your application in your preferred language (e.g,: english).
  2. Create message_XX.properties files for the languages needed for localization, by copying the messages_en.properties file's content under new names, eg.: messages_de.properties. If you previously translated Seam's messages and other JSF related messages into the preferred language, you can copy the already existing properties files from other projects.
  3. Make a backup. This is important since I18nGen tool overwrites all xhtml files and all messages_XX.properties files it founds.
  4. Run I18nGen tool. This will populate the messages_XX.properties files with string literals from the xhtml files with the languge used for development.
  5. Check the properties files. The tool will use the "old" values from the property file. There are three categories listed in the property file:
    1. new property: The property was not found in the original property file, but was on the xhtml page
    2. old but used property: The property was in the original property file but it is also coming from the xhtml page. In this case the old value is not overwritten. If there is a conflict between the new and the old value, this will be listed in the beginning of the property file as a commented line.
    3. old and not used: This means that the property was in the original property file, but not found in the xhtml pages. This could mean the property is for Seam's or JSF messages, but could also mean that you have copied the property from an other project and in your current project that property is not used, so could delete it. It is important to note that if you delete a property, the tool won't place it again in the property file, because in the xhtml page, the String literal was converted into an EL expression, and the tool skips EL expressions.
  6. When you prepared the property file for translation, you should decide if you translate the messages yourself or you pass them to a translator. In the later case, things are a bit complicated because  the property file should be encoded in ISO-8859-1 (Latin-1 charset), and characters not in this character set should be expressed as unicode escape sequences, for example the greek letter  Π (pi) should be expressed as \u03A0, but an usual translator can hardly find every non Latin-1 characrers unicode escape codes, nor he or she can use a developer tool, such as Eclipse's property editor which is capable of handling the character encoding problem. The simplest solution is to send the file as Word document, with the note that existing lines should not be broken and the EL expressions should not be changed either.
  7. The translator does his or her job, then sends back the translated messages in a Word document.
  8. You should convert back the results into the property file. This can be done by opening the property file in Eclipse, then copy-paste the translated content into the opened property file. Eclipse will handle the unicode escaping.
  9. Build your application and deploy it.
  10. You can test the translation by going to every page in your application.
  11. If something is not translated or the meaining is not exactly what you think, you can change the property files. When new pages are added to the application, you can re-run the tool, which will add new properties to the resource bundle property files, and you can restart the translation process.
I18nGen tool


You can download the tool & source code in the form of an executable jar file from here: I18nGen.jar

Usage

From command line the syntax is the following:


java -jar I18nGen.jar <Full path for the directory for xhtml files> <Full path for the directory for the messages_XX.properties>

Example:


java -jar c:\tools\I18nGen.jar c:\workspace\myprj\WebContent c:\workspace\myprj\src


The tool will recursively scan all files with ".xhtml" extension and collects the String literals. The xhtml format is basically XML, so in terms of XML, the tool collects string literals from text nodes and from attributes, where the attribute name is "value", except from the graphicImage tag. The tool excludes literals which has no letters on it (so the Strings which contains only whitespaces and EL expressions are missed out).


The attribute value for the pattern attribute of the convertDateTime tag will be set to 
"#{messages.date_time_format}" and the property date_time_format with the value of "yyyy-MM-dd HH:mm:ss z" will be added.


The messages_XX.properties files will be rewritten in the following form. The first part is the header with a date/time. Then property "collision" information follows. The next part is the section where are properties which is used in the xhtml files but were also in the previous version of the property file. New properties are such properties which are not found in the previous version of the property file, only in the xhtml pages. The last section is for properties which were found in the previous version of the property file, but not in the xhtml pages, so you can think about deleting them (if their names are not begin with "javax.", "validator" or "org.jboss.seam", because these are JSF or Seam related messages)

##############################################
# Generated on Fri Apr 06 13:57:39 CEST 2012
##############################################
# Comments: 
# Property: "configuration_TEXT_Keystore_Password" already exist with value: "3. Keystore Password", the new value would have been: "1. Keystore Password"
# Property: "configuration_TEXT_Certificate_Alias" already exist with value: "3. Certificate Alias", the new value would have been: "1. Certificate Alias"
# Property: "configuration_TEXT_Keystore_File" already exist with value: "3. Keystore File", the new value would have been: "2. Keystore File"
# Property: "configuration_TEXT_Keystore_Password" already exist with value: "3. Keystore Password", the new value would have been: "2. Keystore Password"
# Property: "configuration_TEXT_Certificate_Alias" already exist with value: "3. Certificate Alias", the new value would have been: "2. Certificate Alias"

###############################################
# OLD but USED properties
###############################################

# error
error_TEXT_Error=Error
error_TEXT_Something_bad_happened_=Something bad happened :-(
error_param_false=false

############################################
# NEW properties
############################################

# resource
resource_TEXT_Content_Type=Content-Type
resource_TEXT_Description=Description
resource_TEXT_Download=Download
resource_commandButton_Create=Create
resource_commandButton_Delete=Delete
resource_commandButton_Update=Update

##############################################
# OLD and UNUSED properties (some entries may 
# be removable, except JSF and seam properties)
##############################################

# validator
validator.assertFalse=ellen\u0151rz\u00E9s sikertelen
validator.assertTrue=ellen\u0151rz\u00E9s sikertelen
validator.email=j\u00F3l form\u00E1zott email c\u00EDmnek kell lennie
validator.future=j\u00F6v\u0151beli d\u00E1tumnak kell lennie
validator.length=a hossznak {min} \u00E9s {max} k\u00F6z\u00F6tt kell lennie
validator.max=kisebb vagy egyenl\u0151nek kell lennie a k\u00F6vetkez\u0151n\u00E9l: {value}
validator.min=nagyobbnak vagy egyenl\u0151nek kell lennie a k\u00F6vetkez\u0151n\u00E9l: {value}
validator.notNull=may not be null
validator.past=m\u00FAltb\u00E9li d\u00E1tumnak kell lennie
validator.pattern=meg kell felelnie a k\u00F6vetkez\u0151nek: "{regex}"
validator.range=a k\u00F6vetkez\u0151k k\u00F6z\u00E9 kell esnie: {min} - {max}
validator.size=a m\u00E9retnek a k\u00F6vetkez\u0151k k\u00F6z\u00F6tt kell lennie: {min} - {max}

Tuesday, March 20, 2012

JSF 2 Navigation Pitfalls and Solutions

In this article I will present some cases where JSF 2 navigation will not work; in order the reader can avoid them.


JSF navigation works by first calling the action method (if defined), and from the outcome of the action, the JSF implementation decides which view to display. If there is no action method, a view id can be used directly (e.g.: "landingPage", the file name without extension).


1. Missing <h:form> tag


symptom: By pressing the button (or clicking the link), nothing happens. If there is a <h:messages> tag in the view, the following "cryptic" message is displayed: 


The form component needs to have a UIForm in its ancestry. Suggestion: enclose the necessary components within <h:form>


solution: Put the <h:commandButton> or <h:commandLink> inside a <h:form>
If the <h:commandButton> or <h:commandLink> component is outside of the <h:form>, or there is no <h:form> in the view, no form submit will be generated, so no navigation will occur (and the action method is also won't be called)


2. Missing EL brackets (#{})


Eclipse with JBoss Tools displays the action value with
underline and warning icon, if the EL brackets are missing




symptom: the page is redisplayed, but the action method is not called. If there is a <h:messages> tag in the view, the following error message appears: 


Unable to find matching navigation case with from-view-id '/navigation/page1.xhtml' for action 'navigation.navigateAction1()' with outcome 'navigation.navigateAction1()'


In this case, the button was defined as: 


<h:commandButton
            action="navigation.navigateAction1()"
            value="Missing EL brackets"
/>

solution: Put the action method reference between EL brackets.


note: In this case, the JSF implementation thinks, that what we defined as an action method, is a view id, but it doesn't find a file called "navigation.navigateAction1().xhtml".




3. "void" action method (navigation rule is defined in faces-config.xml)


symptom: The action method is called; page is redisplayed, but no navigation occur, no error message is displayed.


solution: change the action method to return anything (e.g.: a String)


This method:
// doesn't navigate because of void return value
public void doNotNavigateAction1() {
  logger.info("doNotNavigateAction1");
}
should be rewritten to return anything to enable navigation:

public String navigateAction1() {
  logger.info("navigateAction1");
  return "success";
}






4. action method returns null value

symptom: The action method is called; page is redisplayed, but no navigation occur, no error message is displayed.


solution: change the action method to return anything (e.g.: a String value), but not null.

note: This is by design, if the action method returns null, this means, that the previous page should be redisplayed.


Monday, March 19, 2012

Installing new instance of JBoss 7.1.1 with Oracle 10+ database driver and datasource

Installing new instance of JBoss 7.1.1 with Oracle 10+ database driver and datasource
While installing a new instance of JBoss AS 5.1 GA consisted of unzipping the zip file into a directory and copying the jdbc driver into the server's lib directory, installing JBoss AS 7.1.1 requires more work. The following steps describes how to install a new instace of JBoss AS 7.1.1 (and 7.1.0), configure the Oracle JDBC driver and set a datasource.
  1. Download the JBoss AS 7.1.1 from http://www.jboss.org/jbossas/downloads/
  2. Unzip the archive file to a directory (e.g.: D:\bin\jboss-as-7.1.1.Final)
  3. set JBOSS_HOME environmental variable to the unzipped directory (e.g.: "D:\bin\jboss-as-7.1.1.Final")
  4. Run <JBOSS_HOME>/bin/add-user.bat to create an administrator user to be able to log in into the administration interface
  5. Configure Oracle driver & Datasource:
    1. Create directory: <JBOSS_HOME>\modules\oracle\jdbc\main
    2. Download ojdbc6.jar from Oracle (http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-112010-090769.html). Note: ojdbc14.jar was not recognized by JBoss 7.1.0 Final.
    3. Copy ojdbc6.jar into the <JBOSS_HOME>\modules\oracle\jdbc\main
    4. Create the file module.xml with the following content:
    5. <?xml version="1.0" encoding="UTF-8"?>
      <module xmlns="urn:jboss:module:1.0" name="oracle.jdbc"><resources><resource-root path="ojdbc6.jar"/>
          </resources>
          <dependencies>
              <module name="javax.api"/>
              <module name="javax.transaction.api"/>
          </dependencies>
      </module>
      
    6. Edit the <datasource> entry in "\standalone\configuration\standalone.xml", by adding the followings. (Change the _datasource_name_, _jdbc_conncection_url_, _schema_name_, _password_ strings to match to your environment. The datasource name will be referenced by the your application, e.g.: in the persistence.xml)
    7. <subsystem xmlns="urn:jboss:domain:datasources:1.0">
          <datasources>
       ...
       <datasource 
              jndi-name="java:jboss/datasources/_datasource_name_" 
              pool-name="_datasource_name_" 
              enabled="true" 
              use-java-context="true">
                  <connection-url>_jdbc_connection_url_</connection-url>
                  <driver>oracle</driver>
                  <security>
                      <user-name>_schema_name_</user-name>
                      <password>_password_</password>
                  </security>
              </datasource>
              <drivers>
                  <driver name="oracle" module="oracle.jdbc"/>
                            ...
                        </drivers>
          </datasources>
      </subsystem>

Thursday, February 23, 2012

Building and Deploying the Seam 3 Booking example from Eclipse 3.7 to JBoss AS 7.1




This blog entry is about how to make the JBoss Seam 3 Booking Example to build and deploy under Eclipse 3.7 SR2 to JBoss AS 7.1 (under Windows).

There are two maven plugins which could help: The Maven Eclipse Plugin and the APT Plugin from Codehouse.

Maven 3.0.4 and Dependency versions

I got missing version information errors when upgraded to Maven 3.0.4, so I added the version information in every missing place (I have also removed the non JBoss 7 related profiles and testing related   goals) . The modified project pom somehow caused the Eclipse JDT-APT plugin to stop working, so I have added a new builder for running annotation processors (see later). This is how the modified pom looks like:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <version>3.0.1</version>
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.jboss.seam.examples.seam-booking</groupId>
    <artifactId>seam-booking</artifactId>
    <packaging>war</packaging>
    <name>Seam Booking Example</name>
    <description>The Seam booking example using the simplified Java EE 6 programming model and packaging structure (i.e., web archive)</description>
    <url>http://seamframework.org/Seam3</url>
    <properties>
        <jpamodelgen.version>1.1.1.Final</jpamodelgen.version>
    </properties>
    <dependencies>
        <!-- Annotation processor for generating typed loggers -->
        <dependency>
            <groupId>org.jboss.solder</groupId>
            <artifactId>solder-tooling</artifactId>
            <scope>compile</scope>
            <version>3.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.solder</groupId>
            <artifactId>solder-impl</artifactId>
            <scope>runtime</scope>
            <version>3.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-jpamodelgen</artifactId>
            <version>${jpamodelgen.version}</version>
            <scope>provided</scope>
            <!-- Excluded Hibernate-provided JPA API because it's provided by the Java EE 6 dependencies -->
            <exclusions>
                <exclusion>
                    <groupId>org.hibernate.javax.persistence</groupId>
                    <artifactId>hibernate-jpa-2.0-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.jboss.seam.faces</groupId>
            <artifactId>seam-faces-api</artifactId>
            <version>3.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.seam.faces</groupId>
            <artifactId>seam-faces</artifactId>
            <version>3.1.0.Final</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.seam.international</groupId>
            <artifactId>seam-international</artifactId>
            <version>3.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.seam.security</groupId>
            <artifactId>seam-security</artifactId>
            <scope>compile</scope>
            <version>3.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.seam.transaction</groupId>
            <artifactId>seam-transaction</artifactId>
            <scope>compile</scope>
            <version>3.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.picketlink.idm</groupId>
            <artifactId>picketlink-idm-core</artifactId>
            <version>1.3.0.GA</version>
        </dependency>
        <dependency>
            <groupId>com.ocpsoft</groupId>
            <artifactId>ocpsoft-pretty-time</artifactId>
            <version>1.0.7</version>
        </dependency>
        <dependency>
            <groupId>com.ocpsoft</groupId>
            <artifactId>prettyfaces-jsf2</artifactId>
            <version>3.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-digester3</artifactId>
            <version>3.2</version>
            <classifier>with-deps</classifier>
        </dependency>
        <!-- Bean Validation Implementation; provides portable constraints @NotEmpty, @Email and @Url -->
        <!-- Hibernate Validator is the only JSR-303 implementation at the moment, so we can assume it's provided -->
        <!-- TODO Move Hibernate Validator to app server specific sections -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.2.0.Final</version>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.1</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.spec</groupId>
            <artifactId>jboss-javaee-6.0</artifactId>
            <type>pom</type>
            <scope>provided</scope>
            <version>1.0.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.shrinkwrap.resolver</groupId>
            <artifactId>shrinkwrap-resolver-impl-maven</artifactId>
            <scope>runtime</scope>
            <version>1.1.0-alpha-2</version>
        </dependency>
        <dependency>
            <groupId>org.drools</groupId>
            <artifactId>knowledge-api</artifactId>
            <version>5.4.0.Beta1</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.servicemix.bundles</groupId>
            <artifactId>org.apache.servicemix.bundles.drools</artifactId>
            <version>5.1.1_1</version>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
    <build>
        <defaultGoal>package</defaultGoal>
        <finalName>seam-booking</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>apt-maven-plugin</artifactId>
                <version>1.0-alpha-4</version>
            </plugin>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalBuildcommands>
                        <!-- annoyingly creates a bin directory <buildCommand> <name>org.eclipse.wst.jsdt.core.javascriptValidator</name> </buildCommand> -->
                        <buildCommand>
                            <name>org.jboss.tools.common.verification.verifybuilder</name>
                        </buildCommand>
                    </additionalBuildcommands>
                    <additionalConfig>
                        <file>
                            <name>.settings/org.maven.ide.eclipse.prefs</name>
                            <content>eclipse.preferences.version=1
                                   fullBuildGoals=process-test-resources
                                   includeModules=false
                                   resolveWorkspaceProjects=true
                                   resourceFilterGoals=process-resources
                                   resources\:testResources
                                   skipCompilerPlugin=true
                                   version=1</content>
                        </file>
                    </additionalConfig>
                    <additionalProjectFacets>
                        <jst.jsf>2.0</jst.jsf>
                    </additionalProjectFacets>
                    <additionalProjectnatures>
                        <projectnature>org.eclipse.wst.jsdt.core.jsNature</projectnature>
                        <projectnature>org.jboss.tools.jsf.jsfnature</projectnature>
                    </additionalProjectnatures>
                    <workspace>d:\workspace</workspace>
                    <wtpdefaultserver>JBossAS</wtpdefaultserver>
                    <wtpversion>2.0</wtpversion>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <!-- The JBoss AS plugin deploys your war to a local JBoss AS container -->
            <!-- To use, set the JBOSS_HOME environment variable and run: mvn package jboss-as:deploy -->
            <plugin>
                <groupId>org.jboss.as.plugins</groupId>
                <artifactId>jboss-as-maven-plugin</artifactId>
                <version>7.1.0.Final</version>
            </plugin>
        </plugins>
    </build>
    <profiles>
        <profile>
            <id>distribution</id>
            <activation>
                <property>
                    <name>release</name>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-assembly-plugin</artifactId>
                    </plugin>
                </plugins>
            </build>
        </profile>
        <profile>
            <id>jbossas7</id>
            <activation>
                <activeByDefault>true</activeByDefault>
                <property>
                    <name>arquillian</name>
                    <value>jbossas-managed-7</value>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-war-plugin</artifactId>
                        <version>2.0</version>
                        <configuration>
                            <webResources>
                                <resource>
                                    <directory>src/main/resources-jbossas7</directory>
                                </resource>
                            </webResources>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
        <profile>
            <id>jbossas-remote-7</id>
            <activation>
                <property>
                    <name>arquillian</name>
                    <value>jbossas-remote-7</value>
                </property>
            </activation>
            <dependencies>
                <dependency>
                    <groupId>org.jboss.seam.test</groupId>
                    <artifactId>jbossas-remote-7</artifactId>
                    <type>pom</type>
                    <scope>test</scope>
                </dependency>
            </dependencies>
        </profile>
        <profile>
            <id>jbossas-managed-7</id>
            <activation>
                <property>
                    <name>arquillian</name>
                    <value>jbossas-managed-7</value>
                </property>
            </activation>
            <dependencies>
                <dependency>
                    <groupId>org.jboss.seam.test</groupId>
                    <artifactId>jbossas-managed-7</artifactId>
                    <type>pom</type>
                    <scope>test</scope>
                    <version>LATEST</version>
                </dependency>
            </dependencies>
        </profile>
    </profiles>
    <scm>
        <connection>scm:git:git://github.com/seam/examples.git</connection>
        <developerConnection>scm:git:git@github.com:seam/examples.git</developerConnection>
        <url>http://github.com/seam</url>
    </scm>
</project>

Maven Eclipse Plugin

This plugin configures the Eclipse Workspace and creates/modifies the configuration files of Eclipse, so the maven project can be easily imported into Eclipse. I assume, you have imported the Seam Booking example project into your default eclipse workspace.

First, place the following plugin declaration into the <build> section of the pom file (as you have seen under the "Maven 3.0.4 and Dependency versions" section):

<plugin>
    <artifactId>maven-eclipse-plugin</artifactId>
    <version>2.9</version>
    <configuration>
        <additionalBuildcommands>
            <buildCommand>
                <name>org.jboss.tools.common.verification.verifybuilder</name>
            </buildCommand>
        </additionalBuildcommands>
        <additionalConfig>
            <file>
                <name>.settings/org.maven.ide.eclipse.prefs</name>
                <content>eclipse.preferences.version=1
                                   fullBuildGoals=process-test-resources
                                   includeModules=false
                                   resolveWorkspaceProjects=true
                                   resourceFilterGoals=process-resources
                                   resources\:testResources
                                   skipCompilerPlugin=true
                                   version=1</content>
            </file>
        </additionalConfig>
        <additionalProjectFacets>
            <jst.jsf>2.0</jst.jsf>
        </additionalProjectFacets>
        <additionalProjectnatures>
            <projectnature>org.eclipse.wst.jsdt.core.jsNature</projectnature>
            <projectnature>org.jboss.tools.jsf.jsfnature</projectnature>
        </additionalProjectnatures>
        <workspace>d:\workspace</workspace>
        <wtpdefaultserver>JBossAS</wtpdefaultserver>
        <wtpversion>2.0</wtpversion>
        <downloadSources>true</downloadSources>
        <downloadJavadocs>true</downloadJavadocs>
    </configuration>
</plugin>

Now, you can execute the plugin in the seam-booking directory:
mvn eclipse:eclipse

Now the eclipse project should be refreshed, to reflect the changes. If you try to build and deploy the application, it will fail, because the src/test/java directory is configured as source and the content will be included in the resulting war. I simply removed the src/test/java and src/test/resource folders from Project Properties/Java Build Path/Source.

Running the Annotation Processor in Seam Solder
You have several options to run the annotation processor to generate the typed logging class org\jboss\seam\examples\booking\logBookingLog_$logger.java. You can make Eclipse to run it or you can use ant for this purpose. I have used the APT Maven Plugin to configure the .factorypath file to enable running the annotation processor in Seam Solder Tooling, but later after adding the latest versions to the project pom's dependencies, the Eclipse APT was stopped working (no error messages, no results) so I changed to running the annotation processors using javac and ant (see later).  


APT Maven Plugin

This plugin can configure the Eclipse Annotation Processing Tool to be able to run the annotation processor in you maven project.

First, place the following plugin declaration into the build section of the pom file:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>apt-maven-plugin</artifactId>
    <version>1.0-alpha-4</version>
</plugin>


Now, you can execute the plugin in the seam-booking directory:
mvn apt:eclipse

The plugin will change the content of the ".factorypath" file in the project root directory, adding classpath entries to it. Eclipse's APT plugin will search trough this classpath and if an annotation processor factory is found, it tries to execute.

The first thing you should change is the name of the generated source directory. Go to Project properties/Java Compiler/Annotation Processing tab/Generated Source directory text box. Here enter a valid file name (e.g.: ".apt_generated", which is the default by Eclipse).

To see the list of files in the annotation processor classpath, go to the Project Properties/Java Compiler/Annotation Processor/Factory Path tab. The annotation processor for Seam 3 Booking example is found in "M2_REPO/org/jboss/solder/solder-tooling/3.1.0.Final/solder-tooling-3.1.0.Final.jar", where M2_REPO is the eclipse variable for the local maven repository. The Java 6 JDK tools.jar was missing from this factory path, so I manually added as: "D:\bin\jdk1.6.0_31\lib\tools.jar".

If you have installed JBoss 7.1 and configured in Eclipse, you should able to make the war file and deploy it to the application server (I assume you have installed the latest JBoss Tools eclipse plugin).

Using ant to run the annotation processors in your project

The JDT-APT functionality of Eclipse sometimes just doesn't work (see the previous chapter), so my alternative is to use ant and javac compiler to do it. First, create a build file for ant, and save it as build.xml in your project root:

<?xml version="1.0" encoding="UTF-8"?>
<project name="seam-booking-annotation-processing" basedir="." default="apt">
    <property name="src" value="./src/main/java" />

    <target name="apt">

        <javac compiler="javac1.6" srcdir="${src}">
            <include name="**/*.java" />
            <classpath path="${classpath}"/>
            <compilerarg line="-s ${src_gen}" />
            <compilerarg value="-verbose" />
            <compilerarg value="-proc:only" />

        </javac>
    </target>

</project>

Next, you should add a custom builder to your project: Project/Properties/Builders tab/New button:

Use "Ant Builder", then the "OK" button. The following dialog will appear. I have added the name "APT" to this custom builder. The Buildfile name is "build.xml" in the project root (which is "seam-booking" in the workspace)

The interesting part is the arguments for the ant task. The "classpath" parameter is passed to the ant build file containing the classpath, and the "src_gen" parameter contains the full path of the directory where javac will place the generated java code. The directory should be created manually, since javac doesn't create it, if missing.

-Dclasspath=${project_classpath:seam-booking}
-Dsrc_gen=${project_loc:seam-booking}/src-gen

Your builder list for the project should look like this:


Now you should add src-gen to the source paths of your project and do a build (Ctrl-B) to test if the build file is working. If the ant task is executed, it logs to the Console. I have used ant 1.7.1 and Java 1.6 u31.


Troubleshooting

When the application is not deploying, usually the src/test directories are included in the source directories.

When you click on a hotel name, and that results in an exception, this is probably caused by the missing typed loggers which should have been generated during the build process. In this case you should check the error log on why the annotation processor (Solder Tooling) haven't been run properly.

Monday, April 11, 2011

Dynamic Menus in RichFaces

RichFaces has no built-in functionality for creating dynamic menus, the reason for this could be that a lot of different use case scenarios require different type of dynamic menus. This example presents the most simple case: The menu items are dynamically populated from a list, and an action method is called with the id of the menu item, when the user selects the menu item.

The data of a menu item is represented by the MenuItem class:

public class MenuItem {

 /**
  * Id of the menu item
  */
 private int id;

 /**
  * Label for menu item
  */
 private String label;

 /**
  * Constructor
  * 
  * @param label The label fo the menu item
  * @param id the id of the menu item
  */
 public MenuItem(String label, int id) {
  super();
  this.label = label;
  this.id = id;
 }

 /**
  * @return the id
  */
 public int getId() {
  return this.id;
 }

 /**
  * @return the label
  */
 public String getLabel() {
  return this.label;
 }

 /**
  * @param id
  *            the id to set
  */
 public void setId(int id) {
  this.id = id;
 }

 /**
  * @param label
  *            the label to set
  */
 public void setLabel(String label) {
  this.label = label;
 }

 /**
  * @see java.lang.Object#toString()
  */
 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("MenuItem [id=");
  builder.append(this.id);
  builder.append(", label=");
  builder.append(this.label);
  builder.append("]");
  return builder.toString();
 }

}


The dynamic menu is supported by the DynamicMenu class. It provides the list of menu items and an action method:

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

import org.apache.log4j.Logger;
import org.jboss.seam.annotations.Name;

@Name("dynMenu")
public class DynamicMenu {
 
 private Logger log = Logger.getLogger(DynamicMenu.class.getName());

 /**
  * Example action method
  * 
  * @param id the menu item id
  */
 public void action(int id) {
  log.info("Action called with menu item id: " + id);
 }

 /**
  * Returns the list of menu items.
  * 
  * @return the list of menu items
  */
 public List getMenuItems() {

  List menuItems = new ArrayList();

  menuItems.add(new MenuItem("Menu Item #1", 1));
  menuItems.add(new MenuItem("Menu Item #2", 2));
  menuItems.add(new MenuItem("Menu Item #3", 3));

  return menuItems;
 }
}


The following code snippet contains the dynamic menu xhtml example. The key in the dynamic menu items is the <c:forEach> iterator. The namespace declaration is very important, it should be xmlns:c="http://java.sun.com/jstl/core". If you use xmlns:c="http://java.sun.com/jsp/jstl/core" namespace, the iterator won't work!

<h:form xmlns:h="http://java.sun.com/jsf/html">

...

   <rich:dropDownMenu
    value="Dynamic Menu Item Example"
    style="text-decoration: none;"
   >


    <c:forEach xmlns:c="http://java.sun.com/jstl/core"
     var="item"
     items="#{dynMenu.getMenuItems()}"
    >

     <rich:menuItem
      id="menuItem#{item.id}"
      submitMode="ajax"
      value="#{item.label}"
      action="#{dynMenu.action(item.id)}"
     >

     </rich:menuItem>
    </c:forEach>



   </rich:dropDownMenu>

...

</h:form>

Thursday, April 7, 2011

Speeding up a Seam Page in an Expensive Way

The Task

Given a Seam 2.2 application with an overview page displaying progress of students aiming to obtain a given certificate (I have changed the original purpose of the application in this article for discretion). The problem: the page was excessively slow. I was asked to cut the display time from 30 seconds to below 5 seconds.
The page looked like in the following: On the left side there are the "Trainees", on the header there are the "Exams", the other table cells contains the latest dates when a student has taken the given exam and the color shows the status. (The given certificate are previously selected, in this case the "Java Programmer" Certificate).

Declarations, Initialization and Scoping Flow Control API Contents Concurrency OO Concepts Collections / Generics Fundamentals
Alger, Brian 1/3/2011 2/5/2011 3/7/2011 n/a 5/7/2011 6/11/2011 7/19/2011
Algieri, Christopher 1/3/2011 2/5/2011 3/7/2011 4/14/2011 5/7/2011 n/a 7/19/2011
Barnett, Jason 1/3/2011 2/5/2011 3/7/2011 4/14/2011 5/7/2011 6/11/2011 7/19/2011
Dobrin, Adam 1/3/2011 2/5/2011 3/7/2011 4/14/2011 5/7/2011 6/11/2011 7/19/2011
... ... ... ... ... ... ... ...
Fogelson, Benjamin 1/3/2011 2/5/2011 3/7/2011 n/a 5/7/2011 6/11/2011 7/19/2011

Legend:
Finished Failed Waiting



Is There a Cheap Solution?

I wanted to solve the problem by applying some kind of "silver bullet", so I entered "speed up seam application" into google. The most interesting article: Speed up your Data-Driven JSF/Seam Application by Two Orders of Magnitude promised a 100 times ("two orders of magnitude") speed increment by applying the following steps:

  • Remove the unnecessary page action calls
  • Simplify the EL expressions in conditional rendering
  • Avoid calling intercepted methods
  • Avoid using the EL variable resolver, use the corresponding context directly to get the variable's value
  • Reduce the size of the resulting HTML code by reducing the length of IDs, paths; link JavaScript and CSS instead of embedding
  • Disable facelet refresh

Most of the tips are about changing the JSF page or the "page.xml", I have tried my best but with no luck...

Caching

I have tried to use EHCache using this (and some other) guides: Seam and EhCache – A Short Primer. After installing EHCache I have to admit the performance was still low, although after refreshing the page, it was displayed a bit faster.

Investigation

At this point it was clear that no cheap tricks will work, so I had to find out what takes 30 seconds to display the page. Adding ad-hoc instrumentation code into the page action method and into the page xhtml code and by measuring the time using Google Chrome Developer Tools, I found out that

  • 33% of the time spent on database queries and preparing the data in the action method
  • 33% of the time spent on processing the xhtml page and produce the output
  • 33% was spent on displaying the page by the client (waiting for the page data)


First Bottleneck: Data model


By looking at the Hibernate entities and queries, it was astonishing to see how complicated is to collect the data to display the overview. Let us see the data model which is important for the display.


Fig 1. The actual data model
To get a given Certificate the Trainees should take Exams (Certificates and Exams are linked together, but not shown in this model). If a change happens in the Trainee's status (e.g.: finishes an exam), a new Training Event is created linked to a Status. To display the table of all Trainees who are eager to get a given Certificate, the latest Training Events for a given Trainee-Certificate-Exam triplet should be queried. To select the latest training events a sub query is used:


SELECT 
  te FROM TrainingEvent te 
WHERE 
  te.certificate = :certificate AND 
  te.timestamp 
IN 
(SELECT 
    MAX(teLatest.timestamp) 
    FROM 
      TrainingEvent teLatest
    WHERE 
      teLatest.certificate = :certificate 
   GROUP BY 
      teLatest.exam)


Second bottleneck: RichFaces


The number of Exams for a given Certificate is variable and assigned in different parts of the application. To enable displaying dynamic columns for a table, RichFaces has the rich:columns JSF component. In our application this looked like this:

<rich:columns index="ind" style="background-color: #{certificateBean.getLatestTraining(trainee, exam) != null ?certificateBean.getLatestTraining(trainee, exam).status.backgroundColor :'#e0e0ff'};" styleclass="tightTable" value="#{certificateBean.getExams}" var="exam">
    <f:facet name="header">
        <h:outputtext value="#{exam.name}">
    </h:outputtext></f:facet>
    <ui:include src=" /trainingEventPanel.xhtml">
        <ui:param name="event" value="#{certificateBean.getLatestTraining(trainee, exam)}">
    </ui:param></ui:include>
</rich:columns>

The problem with this is the extensive number of calls to
certificateBean.getLatestTraining(trainee, exam)
 
I have eliminated the "heavy" calls to this method to check if rich:columns can be used effectively, but my "experiments" showed using rich:columns inevitably goes hand in hand with a lot of EL expression evaluation accountable for poor performance.

Terminal Solution


I have decided to basically rewrite the whole code, but leave the Hibernate entities alone — changing them would have meant changing the whole application. On the database/entities level I left unchanged everything, but my new logic was to implement a specific cache for the data needed to display the page and on the page I discarded the RichFaces components (rich:dataTable, rich:columns), instead I tried to emulate them with plain and simple HTML <table> tag.

Seam components, displayed in the following figure, are used for caching. The "AppCache" is an Application scope component, which is initialized at the start of the application. It holds the TraineeEventData component which contains the data to be displayed (by Certificate). The TraineeEventDataGenerator component is used to initially "generate" the data or refresh after a change. The TraineeEventDataLoader component is used to query the data from the database, for greater efficiency it uses scalar queries (instead of entity queries) to generate much less network traffic.

Fig. 2: The Caching Components

On the display side, instead of rich:dataTable, simple HTML table is used for display. The rows and columns are displayed by using <ui:repeat> components. The TraineeEventData has a method which can provide the information for the table cells as a linear list, so the HTML generation can be very quick.

<table id="traineeEventTable" class="te_table">
    <!-- header rows -->
    <tr class="te_header_row">
        <ui:repeat value="#{traineeEventTable.getHeaderCells()}" var="cell">
            <td class="#{cell.getStyleClass()}" width="#{cell.getWidthRef()}">
                <s:fragment rendered="#{cell.renderColumnHeader()}">#{cell.getContent()}</s:fragment>
            </td>
        </ui:repeat>
    </tr>
    <!-- normal rows -->
    <ui:repeat value="#{traineeEventTable.getRows()}" var="row" offset="1">
        <tr class="te_normal_row">
            <ui:repeat var="cell" value="#{row.cells}">
                <td width="#{cell.columnIndex==0?'200':''}" bgcolor="#{cell.getBackgroundColorRef()}" class="#{cell.getStyleClass()}">
                    <!-- Trainee names -->
                    <s:fragment rendered="#{cell.renderTraineeHeader()">
                        <table class="te_trainee_table">
                            <tr>
                                <td>
                                    <h:outputText rendered="#{cell.renderTraineeHeader()}" value="#{cell.trainee.traineeDisplayName}" id="traineecell" title="#{cell.hint}"/>
                                </td>
                            </tr>
                        </table>
                    </s:fragment>
                    <!-- not available content -->
                    <s:fragment rendered="#{cell.isNotAvailable()}">n/a</s:fragment>
                    <!-- normal content -->
                    <s:fragment rendered="#{cell.isContentRendered()}">
                        <h:outputText style="color: #{cell.textColorRef};" id="cellcontent" value="#{cell.content}" title="#{cell.hint}"/>
                    </s:fragment>
                </td>
            </ui:repeat>
        </tr>
    </ui:repeat>
</table>


The s:fragment component is used to control generation of entire blocks.

What happens on an update which affects the trainee status table? Originally there was a periodic process using Quartz scheduler to update the table, but it was inadequate for the users. Then I was thinking about making a Hibernate event handler which observes changes in the appropriate entities and updates the data when necessary. The final solution is even simpler, a small utility method is called on those locations when the data is changed:

package com.trainee.util;

import com.trainee.TraineeEventDataGenerator;

import org.jboss.seam.Component;

public class AppCacheUtil {
 /**
  * Calls the Application Cache Updater to update the trainee status table
  * data
  */
 public static void updateAppCache() {

  TraineeEventDataGenerator generator = (TraineeEventDataGenerator) Component
    .getInstance("traineeEventDataGenerator");
  generator.generate();

 }
}


Moral

What lesson we can draw from this case? The first is that the ER model should be always efficient even if the application we are working on is just a prototype (as it were in my case). With a better data model the page display time could have been initially much less. On the other hand the current technology (e.g.: RichFaces) using out-of-the-box is not always able to provide the desired performance and in these cases a custom solution should be made.