blog.smart-java.nl
Ordina J-Technologies – Java Blog

Archief ‘Java EE’ categorie




Running JPA (Hibernate3) and JTA on IBM Websphere 6.1 & 7

Door: Vincent Lussenburg, 5 May 2010

Background

At my current project, we’re currently working on the second release of a webapp that integrates with a couple of webservices. It features a N+1 architecture (pretty much like the J-Technologies reference architecture) integrated by Spring 2.5.x. In this release, we have to persist into a single-consumer Oracle database. Since we have a tight deadline but do want to experiment with various ORM implementations in the future, we ended up deciding to use JPA1.0 with Hibernate3 as persistence provider.

Purpose of this post

The combination Websphere / Hibernate / JPA did provide some – shall we say.. challenges? :) You have some different approach routes to wire these technologies together and having a lot of choices can be confusing. The purpose of this post therefore is not only to show how we integrated it all but also why we did it this way. That hopefully helps others who are starting up a project with these technologies.

And of course, some of the choices we made may be flawed. That’s the reason you can write comments below :)

I created an example project with our setup, see the bottom of this post ([1]). Remember that nowadays you can download a development version of Websphere 7 at no charge at IBM.com. But you can also run this project in jetty ofcourse.

Configuring JPA

Setting up the PersistenceContext

We decided to use Spring to bootstrap the JPA context. This is not the pure JEE way, I’ll get back to that in a later section. Spring’s LocalContainerEntityManagerFactoryBean does pretty much what the JEE container should do: bootstrap the JPA persistence context, but with the usual extra Spring flexibility.

persistence-spring.xml

	

org.hibernate.ejb.HibernatePersistence
		java:comp/env/jdbc/testDb
	

Spring application context
<util:properties id="jpaProviderProperties" location="classpath:jpaVendor.properties" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!--
Non-standard filename so Websphere doesn't try to create the EM (and
throw errors due to Hibernate not being on the AS classpath)
-->
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence-spring.xml" />
<property name="jpaProperties" ref="jpaProviderProperties" />

</bean>

The location of the persistence-spring.xml is important as it is used to find the Entities you want to persist (more info, see here). Ignore the jpaVendor.properties for now, I’ll get to that in the section on integration tests.

Transaction management

Choosing a transaction manager

In the end, we chose the most future-proof option: a JTA Transaction manager (TM). But we started out with these options:

  1. A (in JPA-speak) RESOURCE_LOCAL transaction manager. Spring provides the JpaTransactionManager. Cannot handle transactions for more than one XA resource (db, web service call, etc).
  2. A container-provided JTA transaction manager. Websphere provides the UOWManager and Spring providers a wrapper around it, offering full JTA support – transaction suspending, distributed transactions, the works. It can be created through the container-independent <tx:jta-transaction-manager /> in the spring context.
  3. What is all this transaction manager dogma? Do we need it? What’s wrong with using plain old autocommit?

First: do we need a TM at all? Recent experiences at a different project showed that without a TM the use of connection pools is less efficient resulting in sizeable performance penalties, although it’s not completely clear why. So configuring a transaction manager seems the sensible thing to do. Since JTA is the default choice when running JPA in a JEE container and we had no good reason to reject this option, we went ahead with the default approach. Also, I have the feeling we might have to support WS-Transaction somewhere in the future (yes, YAGNI ;)).

Transaction boundaries

Next: how to configure the transaction boundaries. That’s pretty standard Spring-tx stuff (since we’re not using EJB3). We use Spring’s @Transactional annotations on the service layer (the transaction boundary in our application) and the rest is taken care of by Spring’s <tx:annotation-driven />. Works like a charm.

Hibernate configuration

Hibernate did give some problems with this setup. Since Spring is managing transactions, the only thing Hibernate should do is join the transaction. In order to do this Hibernate needs to look up the transaction manager. Sadly, neither the IBM UOWManager nor the Spring wrapper implements the TransactionManager interface. In the end, this configuration in jpaVendor.properties did the trick:

hibernate.transaction.manager_lookup_class=org.hibernate.transaction.WebSphereExtendedJTATransactionLookup

Bottom line: Hibernate is synchronizing to the transaction using a pre-WAS6.1 mechanism, and Spring is using the >=WAS6.1 way. Also, the Hibernate implementation has it’s problems: setRollbackOnly may be called in application code according to the spec, but this causes a nasty stacktrace in the log. But: it does work correctly. The whole story is explained in detail in this thread.

On a sidenote: something confused me for a while: Hibernate3 configures itself based on the persistence.xml configuration. I noticed that it switched its transaction factory implementation automatically to ‘JoinableCMTTransactionFactory’. CMT is Container managed persistence, and we don’t use EJB2, since this seemed incorrect. After some time I read the javadoc here, and it turns out that this is in fact correct behaviour:

The term ‘CMT’ is potentially misleading here; the pertinent point simply being that the transactions are being managed by something other than the Hibernate transaction mechanism.

Opening the entity manager on each request

We also added a filter (OpenEntityManagerInViewFilter) in the web.xml that sets up a EntityManager that the request starts en destroys it when the request ends (comparable with the OpenSessionInViewFilter for Hibernate).

Running integration tests / Jetty

Our data layer is isn’t unittested, it’s integration tested (as explained by yet another Vincent here). As a rule of thumb, we always try to keep the configuration as identical to the deployment configuration as possible. In this case, the JPA context is set up using the exact same application context file and persistence.xml. The only thing that’s different are the jpaVendor.properties (in tests, I want Hibernate to use the H2 dialect and to automatically create the DB schema). They are read from the classpath (see sping XML snipplet at the beginning of this post): so you can have separate jpaVendor.properties for your test (src/test/resources) and production (src/main/resources) environment [2].

The resources normally provided by the JEE container (through JNDI) need to be mocked in test mode. This is a nice way to accomplish that:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring-config-domain.xml" })
@TransactionConfiguration(defaultRollback = true)
public class UserDaoTest {
[...]
	@BeforeClass
	public static void beforeClass() throws Exception {

		// Suppress the 'close', since we use a single connection in unittest
		// anyways. The connection is terminated upon destruction in afterClass
		singleConnectionDataSource = new SingleConnectionDataSource(
				"jdbc:h2:mem:", true);
		singleConnectionDataSource.setDriverClassName("org.h2.Driver");
		final TransactionAwareDataSourceProxy transactionAwareDataSourceProxy = new TransactionAwareDataSourceProxy(
				singleConnectionDataSource);

		contextBuilder = new SimpleNamingContextBuilder();
		contextBuilder.bind("java:comp/TransactionManager",
				new JotmFactoryBean().getObject());
		contextBuilder.bind("java:comp/env/jdbc/testDb",
				transactionAwareDataSourceProxy);
		contextBuilder.activate();
	}

	@AfterClass
	public static void afterClass() throws Exception {
		contextBuilder.deactivate();
		singleConnectionDataSource.destroy();
	}
[...]
}

So, a datasource is registered in JNDI that keeps one connection open at all times (which is pretty handy when using a single threaded H2 DB) and a JOTM (jottum!) TM is used instead of the Websphere TM. The nice thing is the Spring configuration is identical, the <tx:jta-transaction-manager /> finds the JOTM TM now instead. Hibernate does need some manual configuration:

hibernate.transaction.manager_lookup_class=org.hibernate.transaction.JOTMTransactionManagerLookup

Another bonus: if you want to run your app in a lite JEE container like Jetty for quick deployment, you can use pretty much the same config for that!

Discussion – what about JPA by the JEE book?

According to the EJB3 spec, the container should be in control of the PersistenceContext, roughly as follows:

  • Container detects META-INF/persistence.xml on webapp startup.
  • Container boots the JPA context based on the provided configuration.
  • Container sets the PersistenceContext on objects requiring it.
  • Container exposes the PersistenceContext via JNDI (as defined in the web.xml).

Now try this on Websphere 7 (and 6.1 with the EJB3 feature pack, for that matter). As expected (remember: don’t feed the trolls), Websphere fails if you want to use your own persistence provider (in our case: Hibernate3). According to IBM this should be possible by setting the classloader to PARENT_LAST, but alas, that didn’t seem to work as documented. Messing with heavy weight containers like Websphere is tiresome: you have stop/start redeploy until you’ve gone cross-eyed. So, the pure JEE configuration for JPA in Websphere wasn’t convenient for us (which doesn’t say it’s impossible) and I personally don’t see that as a problem – because it’s just easier to do it the Spring way – which can be easily tested in an integration test, instead of deploy-time.

Final words

So, is this the best solution? THE way of configuring JPA/JTA/Hibernate/WAS? Of course not. The is no right answer here I think, it all depends on the environment you’re in. But by explaining why this seems to be a nice fit for our situation, I hope to help those we need to use these technologies but can’t seem to see the forest for the trees.

Thanks for reading!

Links

[1] example jpa-spring-hibernate-was project
[2] You could also accomplish this by setting a hibernate.properties on your classpath as Hibernate picks this up automatically, but this a more explicit way (but who cares about explicitness anymore in these times of @Autowired magic? :-)).
Keywords: Websphere 6.1 7, JPA, EJB3 , JTA, Transaction management, Spring, Hibernate, Hibernate3




JSF 2.0 ClientBehavior: First impressions

Door: Jan-Kees van Andel, 19 March 2010

In my previous article, I wrote about my first real JSF 2.0 ClientBehavior, called ValidateBeanBehavior.

While programming, I’ve experienced some issues that, in my opinion, make the ClientBehavior less usable in many cases.

Events
A ClientBehavior is attached to a component, both on the server side and on the client side. On the client side, this simply means that an event listener is attached to an HTML element. The event listener then contains the scripts generated by the ClientBehavior.

For example, the generated JavaScript of ValidateBeanBehavior looks like this in the browser.

Do you see the onclick handler on my submit button? This is the ClientBehavior at work. I’ve attached the ClientBehavior to my submit button and you can see what it looks like in the snippet above.

Looks nice, not? No, it doesn’t. You shouldn’t use onclick for validations. Why not? Because the behavior of onclick differs between browsers with regards to form submits. For example, many users use ENTER to ‘implicitly submit’ the form. Different browsers behave differently on such implicit submits, either triggering the onclick of the default submit button (where default is also undefined) or nothing at all.

The current HTML specs are also quite vague about implicit submits. It says the following:

If a form contains more than one submit button, only the activated submit button is successful.

Sounds nice, but what does “activated” mean? When clicking a button, it’s obviously the clicked button, but what to do when pressing ENTER?

Different things may happen in different browsers. For example, in my current Firefox (3.5.8), IE8 and Chrome 4.1 browsers, the default button is the first button (first is determined as the first one in the source).

But in other, mainly older browsers, no click event may be raised. Or, it may raise a click event on the wrong button (the first one after the active input or the first one, based on tab order). This makes it a very unpredictable (and thus not very useful) mechanism.

The HTML5 spec is much clearer about implicit submission and it’s behavior. But, since many users won’t use a HTML5 browser for a while, we simply need a more reliable mechanism, like form.onsubmit. We’ve written our JavaScript validations on onsubmit for years and it simply works. But the standard JSF2 components don’t support it.

Initialization
Another issue with onclick is that it doesn’t provide any window.onload/document.ready support. It simply executes some JavaScript when the button is pressed and there is no way to initialize your JavaScript using a ClientBehavior.

For example, I would have liked to initialize my validateBean JS using the ClientBehavior. This would enable me to provide input masking support.
The mechanism for this needs to be initialized though. Some keyup/-down handlers need to be attached to the form fields and this needs to be done when the page is loaded.

ClientBehavior doesn’t support this. In the ValidateBeanBehavior, I added a @ResourceDependency for my scripts. I can put my initialization logic there, but why should I use a ClientBehavior when all I want to do is loading a JS file? I don’t know.

Default RenderKit
The default RenderKit, HTML_BASIC, attaches the event handlers inline using the “on[eventName]” attribute on the HTML tag. While this is easier for JSF implementers, I generally consider inline event handlers a bad practice. I prefer attaching them in the DOM L2 style: addEventListener (or attachEvent in IE). This allows multiple event handlers and if I really don’t care about this, I still dynamically add them using element.on[eventName]. I think this gives much better markup, because of the separation of markup and scripts.

But, 3th party components may do better here…

Supported components
All components that implement ClientBehaviorHolder may have one or more ClientBehaviors attached to them. Unfortunately, on UIForm, no event named “submit” is supported. And since submit is the most widely used event on forms, this is quite annoying, making behaviors not very useful for standard forms. After all, who wants to handle the dblclick event on a form?

Third party components may of course also implement ClientBehaviorHolder and take advantage of it.

So where is ClientBehavior useful?
Simply put, all client side event handlers you’d like to attach to EditableValueHolder or UICommand components that are triggered explicitly, for example by onchange or onclick events. I can imagine something like effects can be implemented nicely with ClientBehaviors. But OTOH, most effects in real world applications aren’t used standalone, but as a part of an Ajax transaction, so I don’t see much use there either.

The concept of ClientBehaviorHolder is generic and can be applied by any component, so I hope the ICEFaces, RichFaces and Trinidad folks take advantage of this mechanism. I think interoperability between libraries will increase with this.

But maybe I’m just negative because I’d like to completely control my JavaScript.




JSF 2.0 ClientBehavior: Bean Validation in JavaScript

Door: Jan-Kees van Andel, 17 March 2010

In the following article I’m going to show you my first “real world” ClientBehavior and my first impressions from a user’s perspective.

First, some theory. JSF has support for something called “attached objects”. This has been since the very beginning, with Converters and Validators.
Since JSF 2.0, Behaviors have been added to this list. A Behavior, when attached to a component, adds client side scripts to an object. For example, one can imagine a Behavior to do an Ajax request, load some data and show it on the page. This will be a common use case for behaviors. The Expert Group understood this and came up with a specialized AjaxBehavior, which is quite similar to the Ajax4jsf <:a4jsupport /> tag. it adds Ajax functionality to the existing component, without modifying it.

This is ClientBehavior in a nutshell. There are more subtile things to know, see this article by Andy Schwartz for a more thorough explanation of the subject.

From now on, I assume at least basic ClientBehavior knowledge and of course JSF knowledge.

The ValidateBean Behavior
With Java EE 6 we got Bean Validation. And I must admit, I like it a lot. It has a nice declarative language and one ubiquitous model for defining validations for your entire system, from database (generating Bean Validation-aware DDL with JPA 2.0) to UI (the JSF 2.0 BeanValidator, which I implemented for Apache MyFaces. That’s where my enthusiasm started).

But, one validation is missing in the spec (with good reasons of course), namely client side JavaScript validations, to improve usability and decrease server load.

Especially since JavaScript validations are often skipped because of maintenance reasons (validations implemented twice) and we now have a robust platform to implement generic validations, I tried to combine the two new technologies (ClientBehavior and Bean Validation) into one generic JavaScript validator.

The ClientBehavior implementation

This class has some interesting things. First, of course the annotations. @FacesBehavior simply registers the class as a ClientBehavior under the given name, just like how Managed Beans or Converters work. The second annotation defines a @ResourceDependency. A ResourceDependency simply says: “Hey JSF, I generate markup which depends on this file. Make sure it’s available”. And JSF 2.0 responds with: “Okay, I will”.

Also, you probably noticed my ClientBehavior to only understand buttons. That’s right, you need to attach it to a button and it takes care of wiring all field validations in the form.

It also looks for a messages component. This is used later to make sure the JS error messages are positioned the same as the by JSF generated messages. UIMessages applies to the entire view, so I don’t just look in the form. A high performance implementation may choose to start searching near the form, since most messages are positioned there, but that’s way out of scope of this article.

I know, I know, this is not the most elegant piece of code, but it nicely illustrates the point. I simply aggregates as much validation metadata as possible and writes it into one big JavaScript statement. Not that optimal, but high performance implementations may choose to dynamically generate a JS file with all metadata which only needs to be referenced from the inline JS code.

If you’d like to know how to obtain the ConstraintDescriptors (the four method calls in the above snippet), just look for the BeanValidator in the Apache MyFaces SVN. I reused the same code here.

The JavaScript
The JavaScript shown below is part of the static scripts that belong to the ValidateBeanBehavior. It contains the JavaScript code to execute the rules, as passed from the server and, if needed, show the validation errors.

It’s a lot of code, which, in essence, validates all input fields in the given form, according to the given validation rules and shows the user an error if needed. This error is positioned at the same spot as where the UIMessages would have been rendered in case of a server side error. This is a best guess though, because when the messages are not rendered (i.e. on the initial request), there is no marker in the page that I can use for positioning. A more sophisticated implementation could enrich all UIMessages in the page to always write some marker “div” with an ID to the client.

I’m going to skip the rest of the JavaScript. It’s just a bunch of validations and utilities, like utilities to convert Strings to and from Date Objects, based on a SimpleDateFormat pattern. This pattern is part of the generated JavaScript and is obtained by looking at the attached Converters.

Usage in a Facelet
To make the ClientBehavior a bit easier to use, here’s a Facelets taglib which defines a tag for the ClientBehavior (don’t forget to configure the taglib in web.xml or put it in the /META-INF of a JAR).

With the taglib in place, we can use the ClientBehavior, like this:

That’s not too much effort for a client side form validation right? And, these validations are always in-sync with the server side validations.

After a bit of cleanup, I’ll commit the code into the Apache MyFaces Sandbox, so you can download it from there when I’m done. :)




Unit Testing a Bean Validation ConstraintValidator

Door: Jan-Kees van Andel, 12 March 2010

I’ve been playing a bit with Bean Validation and thought I found an issue: Unit testing a ConstraintValidator. Specifically, parametrized ConstraintValidators.

First, what’s a parametrized ConstraintValidator? Simple, a Validator that takes a parameter to do its job. A simple example is a length validator that takes the minimum and maximum length as parameters and validates if the value is between those two.

Parametrized ConstraintValidators are everywhere, even Bean Validation itself contains them. For example: @Min(length) and @Max(length), but also normal ConstraintValidators, like @NotNull where you can customize the error message. However, this error message parameter is not very interesting with regards to unit testing individual ConstraintValidators, because the message is generated by the Bean Validation framework.

For example, consider this ConstraintValidator, incl. corresponding annotation:

In the future, Bean Validation may become the core mechanism for ensuring correctness in your system. For example, JPA 2.0 leverages Bean Validation annotations to generate additional DDL statements and JSF 2.0 automatically uses Bean Validation when it’s available. Note: JSF 2.0 uses a new concept, called “default validators” to implement this. A default validator is invoked on every input component on a postback.

But, how do we test this stuff? After all, you can’t instantiate an annotation.

I currently have 4 options:

Using a declared annotation
The first attempt is shown below. Here, I simply declare the annotation in my test case on a dummy instance field (an annotation doesn’t live on its own) and look it up using reflection. This way, Java takes care of instantiating and initializing the annotation.

I personally quite like this approach. The test data is inside the test case. Unfortunately not in the test method, that would be better, but since you can’t put annotations everywhere in your code, it’s not easy to implement this decently.

So let’s look at the next one…

Custom annotation implementation
Since Java annotations are just a special case of interfaces, they should be fairly straightforward to implement. However, for some reason, I didn’t know this until recently. But it’s actually not different from any other interface implementation. See for yourself.

Nothing special, right? But I don’t really like it. I could have also written it inline, but I don’t like that either:

I think the above one looks like garbage. So this is also a no-go.

Dynamic proxies
Java itself uses dynamic proxies at runtime to instantiate annotations. So why not also use a Proxy to mock the annotation? See for yourself.

However inline, the implementation looks very clumsy. Unfortunately this is probably as simple as it can get, since you DO need to define the inner class.

And it will become even worse when there are multiple parameters on the bean, since you need to check which method is invoked. This will make the implementation even worse.

Mocking using Mockito
But, creating and configuring proxies, isn’t this what mocking libraries do? Exactly, let’s try.

This looks pretty nice. And it scales well with multiple attributes.

I only doubt it will be the nicest solution when the annotations become more complex. I really don’t like annotations that contain annotation parameters. Or even worse, arrays of annotation parameters. But reality is, they exist. And if they exist, they also need to be tested. But, OTOH, people who nest annotations probably don’t mind unreadable unit tests. ;)




REST made easy with Java EE 6 and JAX-RS 1.1

Door: Stephan Oudmaijer, 19 February 2010

In my previous post I wrote about Spring 3.0 and how Spring MVC enables REST services in Spring 3.0. Java EE 6 adds support for RESTfull services by adding JAX-RS to the specification. In this post I will show how JAX-RS 1.1 will make your life easy when writing RESTfull services for JEE 6.

GlassFish v3 is an open source application server and is the first compatible implementation of the Java EE 6 platform specification. To test the examples in this article I will assume that you use GlassFish (or any other JEE6 enabled application server) to run the examples.

Maven2 dependencies

Lets start with the Maven dependencies, you can add them all to the pom.xml of your war. I have also included Sun’s Maven2 repository for downloading the JEE6 dependencies like the javaee-api and Sun’s JAX-RS 1.1 implementation called Jersey.

Both dependencies are scoped as provided because GlassFish already ships with these libraries. In fact, my war file is not bigger than 22kb. JEE6 allowes developers to package full blown JEE application as a web archive file, there is no need for an enterprise archive anymore. This makes JEE6 applications really light weight.

JAX-RS RESTfull services in JEE6

JAX-RS supports configuration through annotations, just like the Spring 3.0 REST annotations. Annotations can be added to both classes and methods. Classes in JAX-RS can be POJO`s. One thing about JAX-RS is that it does not integrate well with other JEE specification, for example the JSR-330 annotations for dependency injection are not supported by JAX-RS (yet), but there is a workaround ;-)

Because of the flexibility of JAX-RS it is possible to annotate EJB SessionBean or CDI components with JAX-RS annotations. So when a bean with JAX-RS annotation is packaged in a war file, the annotations are automatically picked up by the JAX-RS implementation (Jersey in this case). Since EJB3.1 SessionBeans and CDI components support all of the dependency injection features offered by JEE6, JAX-RS now does too!

Below is an example JAX-RS annotated class. The goal of this RESTfull service is to expose two methods of the ProductService through a RESTfull interface. The ProductService is injected using the @Inject annotation.

In JAX-RS the @Path annotation is used to map an URI to a REST service. In the example below I’ve defined the @Path annotation on the class, this will map all the URIs starting with /product to this class. I also defined the @ManagedBean (CDI) annotation on the class for the @Inject to work properly.

There are two methods within the service which are annotated with @Path, @GET and @Produces. The @Path is the same as with the class, but in this case it maps URI’s to a method. The URI of a method is relative to URI specified in the @Path annotation
on the class. So the following URLs are mapped in this example:

  • /product/category/{categoryId} which returns all products in a category
  • /product/categories which returns all product categories
  • JAX-WS allowes for mapping HTTP methods like GET, PUT, POST and DELETE to Java methods with the @GET, @PUT, @POST and @DELETE annotations. In this example only the GET method is used. In RESTfull service the HTTP GET is used to retrieve data. To map a GET request to a method you can simply annotate a method with @GET.

    The @Produces annotation specifies the Mime-Type of the response data the methods produces. In this example the methods both produce XML data, therefore we need to set the Mime-Type to application/xml. When returning an Object from a method annotated with @Produces, JAX-RS trieds to find an appropriate converter to produces the output. In this case I will use JAXB will to marshall the Objects to XML (see below).

    JAXB marshalling

    In order for JAXB to marshall the Objects returned, we need to specify JAXB annotations on the Objects returned from the methods.
    In this example I’ve added @XmlRootElement to the returned Objects to simply marshall the entire Object to XML.

    Adding Jersey to the web deployment descriptor: web.xml

    For JAX-RS to work we still need to add a Servlet to the web.xml which maps URL’s to the services. In this case we need to add the JerseyServlet to the web.xml. In the servlet-mapping all /rest/ URL patterns are mapped to Jersey. We can access the REST services using the following URIs: /rest/product/etc.

    Conclusion

    When building RESTfull services on an JEE6 enabled application server, JAX-RS really makes things easy. You will have to decide for your specific case if you want to use Spring or JAX-RS.

    Orginal article posted here.




    JSF 2.0: The most simple CDI integration use cases

    Door: Jan-Kees van Andel, 31 January 2010

    If you have (just like me) been following the Web Beans and Contexts and Dependency Injection (CDI) work, you might be thinking (also just like I did): “That CDI is heavily over-engineered”. My “moment of clarity” was a year ago, at DeVoxx 2008.

    It was a talk by Pete Muir of JBoss. He was showing a really simple use case and tried to implement it using CDI. The talk was really technology driven and I hated it. Why? Because it wasn’t an improvement compared with the existing technologies. He wrote an application, containing several interfaces, classes (this is not bad) and custom annotations. If the goal was to show some kind of geniosity, it was a good talk. But if the goal was to show how this new technology would make our lives better… then sorry, he failed miserably.

    More than a year further, there have been a lot of movements on the CDI front. And, as an Apache MyFaces developer, I’m of course very interested how to use CDI in a JSF 2.0 application. And as an Apache fanboy, I of course prefer Apache software, in this case MyFaces with OpenWebBeans and OpenJPA.

    Configuration
    Since OpenWebBeans is still under development, you need to do some additional steps to get it to work.

    The following POM should get you up and running quickly in Tomcat:

    <?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/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>org.apache.myfaces</groupId>
        <artifactId>myfaces-example-ebanking</artifactId>
        <version>1.0-SNAPSHOT</version>
        <packaging>war</packaging>
    
        <dependencies>
            <!-- Compile dependencies -->
            <dependency>
                <groupId>org.apache.myfaces.core</groupId>
                <artifactId>myfaces-api</artifactId>
                <version>${myfaces-version}</version>
                <scope>compile</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.myfaces.core</groupId>
                <artifactId>myfaces-impl</artifactId>
                <version>${myfaces-version}</version>
                <scope>compile</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.openjpa</groupId>
                <artifactId>openjpa-all</artifactId>
                <version>${openjpa-version}</version>
                <scope>compile</scope>
            </dependency>
            <dependency>
                <groupId>commons-digester</groupId>
                <artifactId>commons-digester</artifactId>
                <version>2.0</version>
                <scope>compile</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.openwebbeans</groupId>
                <artifactId>openwebbeans-impl</artifactId>
                <version>${openwebbeans.version}</version>
                <scope>compile</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.openwebbeans</groupId>
                <artifactId>openwebbeans-jsf</artifactId>
                <version>${openwebbeans.version}</version>
                <scope>compile</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.geronimo.specs</groupId>
                <artifactId>geronimo-interceptor_1.1_spec</artifactId>
                <version>1.0.0-EA1-SNAPSHOT</version>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>javax.annotation</groupId>
                <artifactId>jsr250-api</artifactId>
                <version>1.0</version>
                <scope>compile</scope>
            </dependency>
    
            <!-- Test dependencies -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <scope>test</scope>
                <version>${junit-version}</version>
            </dependency>
        </dependencies>
    
        <repositories>
            <repository>
                <id>Apache MyFaces beta</id>
                <name>Apache MyFaces beta</name>
                <url>http://people.apache.org/~lu4242/myfaces200beta</url>
            </repository>
        </repositories>
    
        <properties>
            <myfaces-version>2.0.0-beta</myfaces-version>
            <openwebbeans.version>1.0.0-SNAPSHOT</openwebbeans.version>
            <openjpa-version>2.0.0-M3</openjpa-version>
            <junit-version>4.7</junit-version>
        </properties>
    </project>
    

    Note some of the additional dependencies required to run in Tomcat, as opposed to a full blown appserver.

    Also, at the moment you need to build OpenWebBeans from source manually. The geronimo-interceptor_1.1_spec dependency will be downloaded to your local Maven repository on a “mvn install”. OpenJPA is not needed for this simple use case, but I use it in my project.

    Code
    And then, the real code:

    public class WebUtils {
        private static volatile String basePath;
    
        @Produces @Named public String getBasePath() {
            if (basePath == null) {
                basePath = FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();
            }
            return basePath;
        }
    }
    

    This class contains a so-called Producer Method. As the name suggests, it produces stuff. In this case, it produces a String with Dependent scope. This means the method will be invoked every time the variable is needed. EL expressions or injection are the most common cases for this.

    I’m caching the return value, though it’s not necessary, since getting the context path is pretty cheap.

    The view could look like this (snippet):

    ...
    <link href="#{basePath}/style/default.css" rel="stylesheet" type="text/css" />
    ...
    

    Another implementation could put the variable into the Application scope, like this:

    public class WebUtils {
        @Produces @Named @ApplicationScoped public String getBasePath() {
            return FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();
        }
    }
    

    As easy it might seem, the approaches shown above require some responsibility from the programmer though. With producer methods, it becomes really easy to mess things up. After all, you’re effectively creating globals. Tool support may help you here though. For example, the Dependency Analyzer in IntelliJ IDEA 9.0.1 already contains pretty decent support for JSF 2.0 and CDI. And, knowing the reputation of the JetBrains folks, I’m sure they come up with even more fancy stuff.

    A more classic implementation
    A more classic implementation could look like the following:

    @Named
    @ApplicationScoped
    public class WebBean {
        private static volatile String basePath;
    
        public String getBasePath() {
            if (basePath == null) {
                basePath = FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();
            }
            return basePath;
        }
    }
    

    I’m not using producer methods anymore. The WebBean is now a CDI-managed bean.

    The client code becomes slightly more verbose, but who cares? I’ll put the client code in a generic template anyway!:

    ...
    <link href="#{webBean.basePath}/style/default.css" rel="stylesheet" type="text/css" />
    ...
    

    Wrapping up
    I haven’t even showed the complete tip of the iceberg. CDI offers several ways to write code and we’ve yet to find out the (anti) patterns.

    I would like to point you to the OpenWebBeans documentation for more info, but unfortunately this is still under development. The good news is that JBoss Weld already has extensive documentation.