Red Hat

In Relation To Discussions

In Relation To Discussions

The goal of this blog post is to walk you through an Java EE 6 application from a simple, static web page until we have a full blown stack that consist of the stuff in the list below. I'm calling this stack Summer because after a long, hard winter Spring may be nice but boy, wait until Summer kicks in ;-)

  • CDI (Weld)
  • JSF 2 (facelets, ICEfaces 2)
  • JPA 2 (Hibernate, Envers)
  • EJB 3.1 (no-local-view, asynchronous, singletons, scheduling)
  • Bean Validation (Hibernate Validator)
  • JMS (MDB)
  • JAX-RS (RESTEasy)
  • JAX-WS
  • Arqullian (incontainer-AS6)

We will pack all this in a single WAR. Just because we can (spoiler: in part IV). Noticed that apart from the component and testing frameworks, they are all standards? That's a lot of stuff. Fortunately, the appserver already provides most of the stuff so you're app will still be reasonably small.

As for the environment I'm using

  • Eclipse (Galileo SR2)
  • JBoss 6.0 M3
  • Maven 3 (beta1)
  • Sun JDK 6
  • m2eclipse 0.10

This will not be your typical blog post where everything goes well - we will hit bugs. There will be curses, blood and guts and drama and we will do workarounds and rewrites as we move along. Pretty much the same as your average day as a software developer probably looks like. I'm also no expert in the technologies I use here so there are probably things that could be done better. Consider this more of a write-down of my experiences in EE6-land that will probably mirror what others are going through. I will also not point you to links or additional information, I assume that if I say RESTEasy, you can google up more information if you are interested.

And I almost forgot: don't panic.

In the beginning: Project setup

So, lets start things off - go and download the stuff mentioned in the environment if you don't already have it. I'm not going to insult your intelligense by walking you through that (remind me to insult it later). Besides, it's pretty straightforward.

Let's make a new Maven project (File -> New -> Project... -> Maven -> Maven Project. We skip the archetype selection and just make a simple project with group id com.acme, artifact id Greetings of version 1.0.0-SNAPSHOT packed as a WAR. Now finish the wizard and now you should have a nice, perfect project. It will never be this perfect again as our next step is adding code to it.

Maven tip-of-the-day for Windows users. Google up on how you change the path to your local repo as it might be somewhere under Documents And Settings which has two effects: classpath gets huge and there could be problems due to the spaces. Change it to something like c:\java\m2repo

The first thing we notice that m2eclipse has J2SE-1.4 as default. How 2002. Besides, that will make using annotations impossible so lets change that. Edit the pom.xml and throw in


Save and right-click the project root and go Maven -> Update Project Configuration. Aah, that's better


Let's wake up JSF. We create a folder WEB-INF in src/main/webapp and throw in a web.xml because no web app is complete without it (enforced by the maven war plugin). OK, actually this can be configured in the plugin but let's keep the web.xml since we'll need it later.

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="3.0" xmlns=""

and an empty faces-config.xml next to it

<faces-config xmlns=""

and in webapp we add a greeting.xhtml like

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns=""

		<h:outputText value="Hello world"/>

Will it blend? I mean, will it deploy? Do a mvn clean package and you should have a Greetings-1.0.0-SNAPSHOT in your projects target directory. Throw it into the AS server/default/deploy directory and start up the server and go to


The url is not pretty, but the server port, web context root, welcome files and JSF mappings can all be tuned later, let's focus on technologies and dependencies for now. But wait - at which point did we define the JSF servlet and mappings in web.xml? We didn't. It's automagic for JSF-enabled applications.


Next step is bringing in some backing beans, let's outsource our greeting. We make a stateless EJB and use it in CDI

package com.acme.greetings;

public class GreetingBean 
	public String getGreeting()
		return "Hello world";

The @Stateful defines a stateful session EJB (3.1 since it's a POJO) and the @Model is a CDI stereotype that is @RequestScoped and @Named (which means the lifecycle is bound to a single HTTP request and it has a name that can be referenced in EL and defaults to greetingBean in this case). But we have a problem - the annotations don't resolve to anything. So we need to pick them up from somewhere(tm). Fortunately we can have all the APIs picked up for us by adding the following to our pom.xml


Sun Java API artifacts are a bit amusing since getting hold of them can be a bit tricky. First they publish them in the JSR:s and then they treat them like they're top secret. Fortunately Glassfish and now JBoss have started making them available in their repositories (although under their own artifact names, but still)...

We also need to make sure we have set up the JBoss repositories for this according to Have a look at what happened in the projects Maven Dependencies. Good. Now close it and back away. It's getting hairy in there so better trust Maven to keep track of the deps from now on.

The imports should now be available in our bean so we import

import javax.ejb.Stateful;
import javax.enterprise.inject.Model;

and EL-hook the bean up with

	<h:outputText value="#{greetingBean.greeting}"/>

in greetings.xhtml.

Just as no web application is complete without web.xml, no CDI application is complete without beans.xml. Let's add it to WEB-INF

<?xml version="1.0" encoding="ISO-8859-1"?>
<beans xmlns="" xmlns:xsi=""
	xsi:schemaLocation="" />

Package and redeploy. We get a warning about encoding when compiling so lets add this to our pom.xml


Back to http://localhost:8080/Greetings-1.0.0-SNAPSHOT/faces/greetings.xhtml SUCCESS! No. Wait. Huge stack trace hits you for 300 points of damage. Let's back up on our EJB, there are still some issues with 3.1 style EJBs in WAR-only-packaging on AS 6 M3. Remove the @Stateful annotation and it becomes a normal CDI managed POJO. Repackage. Redploy. Recoyce.


Testing is hip nowadays so let's bring in Arquillian. Arquillian is the latest and greatest in EE testing (embedded or incontainer). Start using it now. In a year or so when everone else catch up you can go I've been using it since Alpha. Add the following property to pom.xml:


and these deps


and this profile


Maven will probably now download the entire internet for you.

Let's write our first test and place it in the test source folder:

package com.acme.greetings.test;

import javax.inject.Inject;

import org.jboss.arquillian.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.impl.base.asset.ByteArrayAsset;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

import com.acme.greetings.GreetingBean;

public class GreetingTest 
	GreetingBean greetingBean;

	public static JavaArchive createTestArchive() 
		return ShrinkWrap.create("test.jar", JavaArchive.class).addClass(
				new ByteArrayAsset("<beans/>".getBytes()),

	public void testInjection() 
		Assert.assertEquals("Hello World", greetingBean.getGreeting());


and then we try it out with mvn test -Pjbossas-local-60. If we have the AS running we can save some time, otherwise the manager will start it automagically. Setting the JBOSS_HOME env helps. What happens here is we use Shrinkwrap to create a deployment which consist of our GreetingBean and an empty beans.xml file (for CDI) and the bean is then injected for use in our tests.

This concludes Part I. In part II we will set up ICEfaces and expand our application and in part III we'll set up JPA. Part IV is for MDB and EJB and part V for adding JAX-RS and JAX-WS for importing and exporting stuff.

Simultaneously Supporting JDBC3 And JDBC4 With Maven : II

Posted by    |       |    Tagged as Discussions

As a follow up to, I wanted to point out that I uploaded some example projects to the design discussion. There are 2 different approaches as Maven projects and one Gradle project.

Simultaneously Supporting JDBC3 and JDBC4 with Maven

Posted by    |       |    Tagged as Discussions

Per HHH-2412 and its design discussion I have been working on supporting JDBC4 in Hibernate. Initially I had planned on adding this in 3.6, but now leaning toward 3.5 Anyway, as outlined on the design wiki, I initially thought to add this support as separate modules. However, I quickly came to the realization that using separate modules would actually require users make an explicit choice wrt an extra jar. Especially considering that I could make Hibernate code make this determination programatically, I really did not like that aspect to using modules here. So I started looking for alternatives.

As I normally do, I started by thinking of just the ideal outside of any build structure or tool. So to my mind the best option here seemed to include compiling JDBC4 support targeting JDK 1.6 and JDBC3 support targeting JDK 1.4 and then bundling all that code into a single jar. The code which decides which feature-set to use uses reflection anyway, so there is no issue with having both in the same jar as long as only the correct classes actually get loaded (and anything else would be a bug in this determination code).

Well unfortunately it turns out that Maven does not really support such a setup. In the common case I think you'd set up multiple source directories within that main module and run different compilation executions against them with different compiler settings (source/target). This Maven explicitly disallows (see MCOMPILER-91 and its discussion for details).

Two workable solutions were presented to me (workable in that Maven could handle these):

  1. Use a single source directory, but configure 2 executions of the compiler plugin taking advantage of includes/excludes to define what to compile targeting 1.6 and 1.4. The issue here is that this is not good fit for IDEs.
  2. Split this into 3 modules (one each for JDB3 and JDBC4 support plus another for commonality to avoid circular dependencies with core). Core would then pull the compiled classes from these 3 modules into its jar. Seems overly complicated to me just to work around a self-imposed limitation of Maven. And sorry, I just don't see how this constitutes a messed up system as indicated in that Maven discussion.

Anyway, I really hope someone has other suggestions on better ways to handle this with Maven. Anyone?

Maven, 2 years after

Posted by    |       |    Tagged as Discussions

Let me preface this by saying up front that, yes, I am fed up with Maven. In the 2 years since I decided to switch Hibernate over to use Maven for its build tool I don't think that Maven has lived up to making builds any easier. Quite the contrary, in fact. Previously though there was not really been any other option. At that time ant/ivy combo was just starting to gain traction. Not to mention that I do like the notion of build-by-convention which Ant just does not provide.

Bugs aside, most of the problems I have with Maven in dealing with Hibernate stem from Maven's assumption that all projects are independently releasable. The problem here is that this extends to sub-projects or modules as well. With Hibernate, the decision to utilize sub-projects was made solely for the purpose of isolating dependencies to various pieces of optional Hibernate functionality. For example, we have a sub-project specific to dealing with c3p0 as a provider of JDBC connections. The dependency in Hibernate on the c3p0 artifact is isolated completely in this module. So as a user you can simply tell maven that you are using hibernate-core and hibernate-c3p0 and have the transitive dependencies set up correctly. I did not set up these sub-projects so that I could release hibernate-c3p0 independently at some time. I have no desire do go that route as it causes nothing but confusion IMO. Even if nothing were to change in the classes in hibernate-c3p0 I would much rather have that get bumped to the new standardized version.

So anyway, what are the issues with this assumption? Well the first is that I cannot simply 'change directory' into a sub-project directory and build it and expect Maven to build the other projects upon which this sub-project depends for me automatically. For example, I cannot 'cd' into the hibernate-c3p0 project directory and run 'mvn compile' and expect Maven to first compile the hibernate-core project for me even though hibernate-c3p0 depends upon it. This may not sound like a big deal, but Hibernate is a big project with 14 jar-producing projects (not to mention numerous support projects like documentation and distribution-builders). Having to 'cd' around all those different projects just to compile a dependency graph that Maven already know about seems silly. But again, Maven must do this because of this assumption of project independence

The other issue has to do with the notoriously bad support for performing releases. This has bitten me every time I have tried to do a Hibernate release with Maven using it's release plugin. In fact it just caused a 3 day delay in the Hibernate 3.5.0.Beta-1 release. I know the release plugin is just a wrapper around a few mvn commands you can run yourself (in fact that's how I finally ended the 3 day 3.5.0.Beta-1 release marathon); the issue is again back to Maven's support for multi-project builds. The release plugin is the only current plugin which offers support for managing the numerous version declarations that are required throughout all the sub-projects. So when releasing a project with multiple sub-projects you have 2 options: (1) use the release plugin or (2) (a) update the pom versions manually (b) commit (c) r-tag (d) update the pom versions manually (e) commit (f) checkout the tag (g) perform the mvn deploy. Sure would be nice if the version management stuff from the release plugin were usable separately.

The other build tools I have been looking at briefly are (1) gradle, (2) buildr and (3) simple-build-tool. Anyone have practical experience with any of these, or suggestions on others we should look at?

jDocBook and resource+content staging

Posted by    |       |    Tagged as Discussions

<queue-voice-of-god>In the beginning there was jdocbook-styles...</queue-voice-of-god>

jDocBook styles were meant to represent common styling elements that could be developed on their own, built into bundles and used as dependencies to DocBook builds using the jDocBook plugin. The contents of the styles (css and images) were staged to a special directory within the DocBook project's target directory for use within the XSLT formatting.

Recently I have been working on extending that concept to an idea from the world of publican. For those not familiar with it, publican is the DocBook build system used by Fedora and many Red Hat related projects. The idea I was looking at including into the world of jDocBook is what publican terms brands. These brands really provide two somewhat complimentary things:

  1. styling
  2. fallback content

Much like jdocbook-styles, publican brands allow providing css and images that should be used in the output formatting. The big difference is that brands allow for them to be localized to the particular translations. The notion of 'fallback content' allows common pieces of content (DocBook XML) to be developed and then used throughout various documentation projects. For example, the publican brands generally define fallback content for things like legal notices and document conventions. Again, allows for localization to the various translations in terms of appropriate POT/PO files.

The localization aspect brings up a question wrt jdocbook-styles and the staging of those resources. Currently the resources within a jdocbook-styles are staged into the target/docbook/staging directory by the jdocbook plugin itself (the later formatting phase simply points to them from there for each translation since they are implicitly shared for all translations). Staging of the brands, however, would require that each translation have its own staging directory (ala target/docbook/staging/en-US, etc). So either the jdocbook-styles could be repeatedly exploded into each translation's staging directory or we could make the move to have localized jdocbook-styles as well.

Initially the idea was to have the jDocBook plugin itself perform all these stagings (especially since it does so already for jdocbook-styles). But today another thought crossed my mind: separate out the notions of staging. The basic principle would be to simplify jDocBook to focus on a core competency, namely taking some DocBook XML, some resources, some XSLT and generating some formatted output. This would allow projects not using styles and not using brands to have a very simple jDocBook setup; essentially it would build directly from the controlled sources. For projects with styles and/or brands we would stage everything to the staging directories and configure jDocBook itself to use the staged directories as its input.

--- Resources:

  • GNU gettext if you are not familiar with POT/PO files
  • poxml for the tools used to handle gettext in regards to XML files

It's time for Facelets to start using XSD

Posted by    |       |    Tagged as Discussions JSF

I've had this idea for a while now about using XSDs in Facelets templates. I believe we should stop pretending that Facelets templates are XHTML documents and start treating them as unrestricted XML. This would give us the freedom to extend the XML dialect with XML Schema and take full advantage of the type enforcement, syntax recognition, and tooling support that XML Schema provides.

I tried to communicate this idea to the JSF EG at JSFOne, but I fear that I did not articulate it well enough as it never took hold. I want to explain the approach here in detail to see if others agree it has merit. In this entry, I outline a way to take better advantage of Facelets' strengths today and propose a change in JSF 2.1 to support this usage. Right now, all I'm doing is putting the idea out there in the open.

A brief intro to Facelets

Anyone familiar with JSF must have heard about Facelets by now. Facelets is the alternative view handler and view definition language to JSP for JSF, and a far superior one at that. But Facelets is more than just an alternative. I truly believe that Facelets saved JSF, for if it weren't for something elegant like Facelets to come along and give developers a reason to give JSF a chance, they would have abandoned the framework long ago. Facelets really is that significant. As a recognition of its influence, Facelets is set to become the standard page declaration language in JSF 2.0--so if you have been living under a rock, you'll have to come out of hiding soon enough.

What makes Facelets successful

There are two features of Facelets that make it a more palatable choice than JSP for UI development:

  1. The XML markup gets translated directly into JSF UI components
  2. The XML markup must be well-formed

The first point is important because it means that the middleman in the view template to component tree build process has been ousted. JSF was originally designed so that it could leverage JSP pages and in turn JSP tag handlers. Each JSF component was mapped one-to-one with a JSP tag handler. That meant JSF didn't have to be in the business of consuming and parsing XML (or pseudo-XML in the case of classic JSP syntax). Instead, JSP would feed UI components to the JSF component tree build process.

While this sounded good from a reuse perspective, it turned out to be a terrible nightmare for developers. The JSP tag handlers duplicated the properties of the combined UIComponent and component renderer classes for each component. This meant one more class for the developer to write and one more class to maintain. Not to mention the burden of having to keep the tag library descriptor (TLD) metadata in sync with the class to make the JSP parser happy. To minimize the effort, many developers turned towards code generation, in this case an indication of a badly broken design.

Enter Facelets. Facelets offers its own XML compiler and tag handlers. Only in this case, the tag handlers are generic and require minimal configuration. Facelets can introspect the UIComponent and component renderer classes to determine how to map the information from the XML document into objects in the JSF component tree, both of which the Facelets builder creates. Facelets effectively cuts out the middleman. What's more, by having control over the compile process, Facelets was able to introduce its own advanced templating mechanism (called compositions) that allow one Facelets template to become the template of another, almost resembling a LISP dialect.

While building direct is an important reason for Facelets' success, the second point listed above is the one most relevant to this entry. Facelets put its foot down by enforcing valid XML syntax, finally doing away with that ridiculous pseudo-XML syntax that classic JSP supported. Even the JSP taglib directives were removed in favor of using XML namespace declarations to import a component set.

Facelets == XML

If you have so much as an undeclared entity in your template, Facelets will abort processing and throw up a pretty (no, really!) error page. And when Facelets reports the error, it can do so with precision (e.g., line number and column) since it uses a SAX compiler to parse the template prior to building the component tree.

Now I'll convince you why using valid XML is a good thing.

Leveraging the XML ecosystem

XML is ubiquitous. As a result, there are probably as many XML editors available as there are e-mail clients. By Facelets enforcing valid XML syntax, it means I don't have to wait around for a vendor to create me an editor to support a proprietary syntax, as was the case with JSP. Instead, Facelets opens the door to using any one of the available XML tools to create/modify/translate a Facelets view template. That's a very important benefit.

But there's a catch...well, really just a snag. In an attempt to support an experimental design-time technique, Facelets veered off course and did not take full advantage of the tooling benefit that XML has to offer. Let me explain what Facelets' creator was going for and then show you how to take advantage of what he missed.

By parsing the template directly, Facelets is able to work around one of the most horrible monstrosities of the early JSF-JSP integration, the <f:verbatim> tag. You see, every character in a JSF response must be yielded by a JSF component. That means that all static HTML markup must somehow get attached to a component. The only way to accomplish this in JSP was to introduce a wrapper tag, <f:verbatim>. However, this tag not only makes the template look ugly and verbose, it also makes creating valid XML nearly impossible because it ignores the HTML structure.

Once again, Facelets saved the day. Any time Facelets comes across static markup, it automatically creates a UIComponent to wrap the markup and output it during encoding. This also means that Facelets templates can match the recipe of JSP pages: static HTML markup with dynamic parts intermixed.

But Facelets goes a little too far by assuming (in the general case) that the document itself is an HTML template interspersed with JSF components. It became conventional to include an XHTML DOCTYPE at the top of the page (at least the top-level template), which Facelets then passes on to the response when the component tree is encoded. Facelets even takes measure to hide the JSF components by allowing them to be defined on a standard XHTML tag using the proprietary jsfc attribute (the name of the JSF component tag is defined as the value of the attribute). The theory here is that when the template is opened in an HTML viewer, it renders just like any other static HTML document, thus allowing the designer to preview the page. In theory.

<ul jsfc="ui:repeat" var="_name" value="#{bean.names}">

In reality, this theory simply doesn't scale. Unless all you are doing is developing a mostly static website with a handful of dynamic parts scattered across a subset of pages, you eventually get to the point where the pretend HTML documents become a handicap for both the page designer and the developer. It especially hurts the developer because it limits his/her ability to reuse template logic or roll it up into a custom component. I have done a lot of web development and the only way that this relationship works is if you are using a tool, such as the JBoss Tools visual designer, which can provide a runtime view of the page at design time. Otherwise, the designer should simply work on his/her own mockups and deliver them to the developer when they are ready to be integrated into the application.

Cutting the XHTML shackles

While Facelets templates are valid XML, most developers treat them as XHTML documents. The problem is, the XHTML vocabulary is not extensible, particularly when the document is tied to a DOCTYPE. That means all those JSF component tags in the document are seen as foreign bodies and cause the XHTML parser to complain loudly. Once again, you have to wait on that vendor to create an editor which supports this proprietary syntax. And what does that support look like? Well, likely the editor is going to have to parse the TLD files and provide some sort of code assistance (i.e., tag auto-completion) based on that metadata. Proprietary, proprietary, proprietary. Yuck.

But wait, didn't we just finish emphasizing that a Facelets template is valid XML? Of course! Well, there's a perfectly good vocabulary extension system for XML called XML Schema. XML Schema associates an XML dialect with an XML namespace. Unlike DTD, this contract permits multiple vocabularies to be imported into a single document, thus allowing it to be extended infinitely. In addition, the specificity of XML Schema goes way beyond what DTD allows. In fact, XML Schema is so detailed that with its support, you could call XML a type-safe language. This type system translates into code assistance and validation, drastically reducing the pain involved with using XML.

And guess what? Many of the configuration files for the Java frameworks you use today rely on XML Schema Documents (XSDs) to describe, extend, modularize, and document the permissible elements and attributes. Here are a couple of examples:

  • Seam's component descriptor (components.xml, .component.xml)
  • Seam's page descriptor (pages.xml, .page.xml)
  • Faces configuration resources (faces-config.xml)
  • Web application descriptor (web.xml)
  • Spring configuration file

So why not add Facelets to this list? Nothing is stopping us! All we have to do is author an XSD for each JSF component library we use (e.g., Facelets UI, JSF core, HTML basic, etc) and import the types defined in the XSD by associating it with the component library's XML namespace.

Creating XSDs for each component library sure would be a tedious task. You'd have to define an element for each component tag and then list all of the component-specific and renderer-specific attributes. We'll, don't throw away those TLD files just yet! As Mark Ziesemer points out, a TLD file is XML too. So you can work smarter, not harder, by writing an XSLT document to transpose the TLD into an XSD. And fortunately for us, Mark did that for us already! I used his XSLT script to create XSDs for the standard JSF component sets. Once created, I match them up with namespaces in the xsi:schemaLocation attribute as shown below. Note that to use this attribute, it's necessary to declare the namespace for XML Schema.

<?xml version="1.0" encoding="UTF-8"?>
<f:view xmlns=""
    xsi:schemaLocation=" facelets-ui-2.0.xsd jsf-core-2.0.xsd html-basic-2.0.xsd">
            <h2>My name is Duke. What's yours?</h2>
            <h:form id="helloForm" prependId="false">
                <h:graphicImage url="/wave.png"/>
                <h:inputText id="name" value="#{}"/>
                <h:commandButton id="submit" action="success" value="Submit"/>
            <h2>Folks who stopped by to say "Hi!"</h2>
                <ui:repeat var="_name" value="#{GuestBook.names}">

If you were to open this document in any XML editor that is capable of digesting XSD and providing code assistance (which is pretty much any XML editor) you now get tag completion for standard JSF component elements and attributes in addition to standard HTML attributes! Try it out for yourself by downloading the sample code[1] attached.

The only slight drawback is that the root tag is not <html>, so you don't get the out of the box preview with a standard HTML viewer. Assuming that matters to you, the problem with making <html> the root tag is that HTML does not accommodate other vocabularies in the document. The schema for HTML lacks <xs:any> declarations that would allow foreign tags to be present. And unfortunately, the HTML schema is pretty much fixed in stone. There is an effort for modularizing XHTML, but it still isn't widely adopted. For now, it's easier just to interweave HTML tags into the <f:view> document root than it is the other way around.

Now, you might be thinking that creating the XSDs is just one more step in a long process to create a JSF component library. I'm here to say that the transformation from TLD to XSD should be a migration away from TLD in favor of XSD. XML Schema is an incredibly comprehensive at defining XML dialects and there is absolutely nothing that TLD can describe that XML Schema cannot. Unlike TLD, XSD even has the ability to declare which facet names a component supports. Scrap TLDs!

What's your type, Doc?

There's one shortcoming in this setup. We had to remove the DOCTYPE definition at the top of the document so that the XML editor doesn't complain about the presence of the JSF component tags (which are obviously not declared in the XHTML DOCTYPE). XML Schema is a replacement for DOCTYPE and as such, the two are mutually exclusive. But if you think about it, the DOCTYPE is not there to validate the syntax of the template. It's really part of the output, meant to instruct the browser how to render the page. Therefore, the DOCTYPE should be rendered by a component tag just like any other markup-producing area of the template.

Unfortunately, the standard HTML component library does not include a tag that outputs a DOCTYPE. But you can quickly define a prototype of this tag using a JSF 2.0 composite component (or you can go all the way and create a real UIComponent). The following fragment from the file resources/meta/doctype.xhtml defines the <meta:doctype> tag as a composite component:

<comp:interface name="doctype" 
    displayName="XHTML DOCTYPE"
    shortDescription="Produces an XHTML DOCTYPE declaration">
    <comp:attribute name="type" required="true"/>
    <h:outputText value='&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 #{
        fn:toUpperCase(fn:substring(compositeComponent.attrs.type, 0, 1))}#{fn:substring(compositeComponent.attrs.type, 1, -1)
        }//EN" "{compositeComponent.attrs.type}.dtd"&gt;' escape="false"/>

Then you simply add this tag directly inside of <f:view>.

<?xml version="1.0" encoding="UTF-8"?>
<f:view xmlns=""
    xsi:schemaLocation=" facelets-ui-2.0.xsd jsf-core-2.0.xsd html-basic-2.0.xsd">
    <meta:doctype type="strict"/>

It's pretty clear that the standard HTML component library should include a component tag capable of producing all of the valid HTML and XHTML doctypes. There's no reason a developer should have to assume the burden of something that is so fundamental to web page development.


Tell me what you think of this idea. Do you think it will help development? Do you think it will lead to better tooling? If it's worth pursuing, I think the XSDs should be built automatically from the metadata in the standard faces-config.xml and through reflection of the component classes/renderers so that you, the developer, don't have to worry about creating them and making them available on the file system. And of course, the tooling should help you get the XSDs added to the template.



Step right up and select your time zone

Posted by    |       |    Tagged as Discussions JSF

Prior to revision 2.0, the JavaServer Faces specification states that all dates and times should be treated as UTC, and rendered as UTC, unless a time zone is explicitly specified in the timeZone attribute of the <f:convertDateTime> converter tag. This is an extremely inconvenient default behavior. This open proposal, targeting the 2.1 release, extends the Locale configuration to accommodate a default time zone preference that is used by default when a date is rendered.

Note: Dates are always assumed to be defined using UTC, so this proposal merely addresses the display offset.

Making the system time zone the default

The JavaServer Faces 2.0 (proposed) specification offers a way to override the standard time zone setting of the JavaServer Faces application so that it uses the time zone where the application server is running (which happens to be the default behavior for Java SE according to java.util.TimeZone) rather than UTC. This override is activated using the following web.xml context parameter declaration, documented in section 11.1.3:


Before diving into the implications of using the system time zone, I want to first suggest either renaming this parameter or removing it in favor of a comparable setting defined in faces-config.xml. Assuming the context parameter remains the preferred way of making the system time zone the default, there's no way anyone except JSF experts will be able to commit this parameter to memory due to its unnecessarily long name. I would like to put forth an alternate, simpler name:


In addition to name being shorter, it's much less specific, opening the door for other areas of JSF to take advantage of this setting. (An alternative configuration defined in faces-config.xml is proposed further down).

Naming aside, this setting is important because it allows the developer to restore the default time zone behavior of the JVM. However, it does not address the real problem that JSF was attempting to solve, which is that the time zone used by the application should not be affected by the geographic location of the deployment. Optimally, the default time zone should reflect the time zone preference of the user (i.e., it should be a user time zone).

Setting the default time zone in JSF

Time zones are extremely important in data-driven web applications. That's why the JSF runtime should make it easy for the developer to get the time zone setting correct. Both the UTC and the system default time zone choices are inadequate. The UTC default is annoying because it forces every developer to deal with the time zone issue on day one (no good default). The system default is risky because it's dependent on the geographic location where the application is deployed.

Let's consider a scenario where the system default is inadequate.

If I am deploying my application to a server in California and servicing New York customers, the default time zone is not what the customers expect. Now, I could start my application server instance with the time zone of New York. But what if I have a separate application on that server that services customers in California? Then I have a major conflict.

The correct solution is to allow the time zone to be set per JSF application, configured in faces-config.xml. In fact, there is already an ideal place to define this configuration: within the <locale-config> element, complementing the default locale. The developer would specify a time zone ID in the new <default-time-zone-id> element and JSF would resolve a TimeZone object from this ID. Here's an example showing the default time zone set to New York.


However, a static value is not always sufficient since the users of an application may reside in different time zones. Therefore, while a static value is permitted, this element should also accept a ValueExpression that is resolved when the time zone value is needed (i.e., such as during encoding). The permitted use of a ValueExpression allows the default time zone to be dynamic, but still a default since it can be overridden by the <f:convertDateTime> component tag.


This configuration setting provides three important features:

  1. Provides a good application default (which may be customized to the user's preference using a ValueExpression)
  2. Remains stable across deployment locations (doesn't change just because the application is deployed to a different time zone, as is the case with the system default)
  3. Isolated per application running on the same server

With this feature available, JSF will perform the following time zone resolution algorithm.

If a default time zone ID is specified in a configuration resources (i.e., faces-config.xml), then the TimeZone resolved from the specified ID is used as the default time zone in the JSF application. If one is not specified, JSF will use the system default time zone if the javax.faces.USE_SYSTEM_TIMEZONE context parameter value is true or UTC otherwise.

But instead of relying on a context parameter to set the time zone to the system default, it may be better to introduce the <system/> element as a possible value for <default-time-zone-id> to keep the time zone setting contained within the JSF configuration. (Context parameters in the web.xml configuration should only be used for defining implementation-specific settings).

The addition of the <default-time-zone-id> child element in <locale-config> requires the following API additions to javax.faces.application.Application.

  * <p>Return the default <code>TimeZone</code> for this application. This
  * method resolves the Value Expression returned by {@link Application#getDefaultTimeZoneId}
  * and uses that value to look up a <code>TimeZone</code> instance. If the
  * resolved time zone id is null, the <code>TimeZone</code> for UTC is returned.</p>
public abstract TimeZone getDefaultTimeZone();

 * <p>Set the default time zone for this application as a value expression that
 * is expected to resolve to a time zone id.</p>
 * @param timeZoneId The new default time zone
 * @throws NullPointerException if <code>timeZone</code>
 *  is <code>null</code>
public abstract void setDefaultTimeZoneId(ValueExpression timeZoneId);

 * <p>Return the default time zone for this application as a value expression
 * that is expected to resolve to a time zone id.<p>
public abstract ValueExpression getDefaultTimeZoneId();

What about auto-detecting the user's time zone?

The main challenge is that browsers don't send a preferred timezone header like they do a preferred language header. And you can't rely on a geo-IP address resolution since VPNs and other network configurations can move the source address across timezones. For now, it's the application's responsibly to collect the user's preference and store it in either the database or a browser cookie. The ValueExpression defined in the <default-time-zone-id> element is expected to return this stored value.

Provide your feedback

Let me know what you think about this solution. Does it seem adequate? Do you think the configuration is simple enough? Am I missing something? (Please see the JSF 2.1 page on the Seam Wiki for the latest revision of this proposal).

I encourage you to start participating now in these and other issues so that JSF can continue to improve as a result of community participation and feedback. JSF 2 is a big step in the evolution of JSF, but it is by no means the last.

What methods belong on an entity?

Posted by    |       |    Tagged as Discussions

Kinda tangentially related to this discussion, I'm often asked whether I believe in rich domain models or anemic domain models. I guess I'm pretty much ignorant as to what these terms really mean, since I've never seen a proper definition of either term.

If by anemic domain model, we mean /never/ writing any business logic on our object model, and if by rich domain model, we mean /writing as much business logic as possible/ on our domain model, then I certainly don't believe in either approach. But these seem to be caricatures; I don't think anyone follows either extreme.

So how do /I/ decide if method that implements business logic might belong on the domain model?

Well, here I'm guided by an understanding that the domain model (entity classes) are /the most reusable/ classes in my codebase. So I don't want to put any logic there that has dependencies to any state or collaborating classes /other than/:

  • state held in the domain model (the persistent attributes), and
  • other domain model classes.

In particular, I would never write code that calls out to external services, or accesses the database, or calls an EJB/Seam/Spring component in my entity class. I want my domain model to be /completely self-contained!/

So anytime you find yourself wishing that entities supported injection, or find yourself writing a JNDI lookup in a method of an entity, please consider that your domain model is no longer self-contained, and will be less reusable in different execution environments.

I'm not saying it's /wrong/ to disobey these rules. There's no right or wrong in design. But I think there's good value having a self-contained domain model, and I've never seen a situation where this idea was impractical.

Want to use Seam with Maven?

Posted by    |       |    Tagged as Discussions Seam

Since I posted that Seam was now available in Maven, both Michael Yuan and Wesley Hales have blogged about creating a Seam project with Maven, including automagically setting up Tomcat with JBoss Embedded (cool, huh!) and deploying the project to it.


back to top