Google XML Pages

Published: 12:08 AM GMT+12, Monday, 4 August 2008 under: technology
google  template  java 

In the original incarnation of my simple time tracker application I had used freemarker as a template engine for the email report. For this new incarnation I thought I'd take the newly open sourced Google XML Pages (GXP) for a spin.

Unlike JSP pages which generate and compile .java files on the fly, GXP generates .java files up front as part of your build process and forms a type safe API to the rest of your application to use. Just as Apache Wicket brings type safety to your web applications Session and Pages, GXP brings it the same power to your templates.

A short example is the Work Item Summary template:

<gxp:template name='com.theoryinpractice.timetrackr.gxp.WorkItemSummary'
              xmlns='http://www.w3.org/1999/xhtml'
              xmlns:gxp='http://google.com/2001/gxp'>
  <gxp:import package="java.util"/>
  <gxp:import package="com.theoryinpractice.timetrackr.vo"/>
  <gxp:import package="com.theoryinpractice.timetrackr.pages"/>
  <gxp:param name="reportForDate" type='String'/>
  <gxp:param name="formattedTimeFor" type='String'/>
  <gxp:param name="activities" type='List{ActivityReport}'/>
  ...

Once generated and compiled, this is called in java with:

List<ActivityReport> activities = new ArrayList<ActivityReport>();
...
StringBuilder buffer = new StringBuilder();
WorkItemSummary.write(
  buffer, new GxpContext(Locale.getDefault()),
  reportForDate,
  TimeFormat.format(userManager.calculateTimeForUser(user, Boolean.FALSE)),
  activities
);

The generated API is clean and simple to use, a single method to call with the required parameters and you're away laughing. Comparing this with how I've used velocity and freemarker in the past, I can already see several benefits:

  • You break your template, you break your build.
  • If you add/remove parameters to a template without changing the code, you break your build (I'd rather have a build broken in 5 places, than have a deployment break in the 1 that was used by QA guy #3)
  • Templates are now first-class citizens in your application
  • Templates can easily be bundled/modularized (and safely used across class loaders - OSGi I'm thinking of you!)

The GXP template may be a little bit more wordy than the original freemarker version, but the safety it brings to the build is well worthy the XML.

Comments (1)

"Templates can easily be bundled"

Great idea! I never thought of this...

left by Ignacio Coloma . Monday, 4 August 2008 6:40 PM
Add Comment