<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Andy Gibson &#187; EJB</title>
	<atom:link href="http://www.andygibson.net/blog/tag/ejb/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.andygibson.net/blog</link>
	<description>Open Source Projects &#38; Technical Writings</description>
	<lastBuildDate>Fri, 30 Jul 2010 02:42:19 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Getting Started with JSF 2.0 and CDI part 3 &#8211; Events</title>
		<link>http://www.andygibson.net/blog/tutorial/getting-started-with-jsf-2-0-and-cdi-part-3/</link>
		<comments>http://www.andygibson.net/blog/tutorial/getting-started-with-jsf-2-0-and-cdi-part-3/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 13:26:45 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[Weld]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=728</guid>
		<description><![CDATA[Last time we looked more in depth at CDI and how we can define beans and inject them into other beans. This time we are going to look at how we can use events to decouple the handling of actions in the system.

Read Part 1
Read Part 2
Read Part 3
As a refresher, in our last part, [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.andygibson.net/blog/index.php/2009/12/22/getting-started-with-cdi-part-2-injection/">Last time</a> we looked more in depth at CDI and how we can define beans and inject them into other beans. This time we are going to look at how we can use events to decouple the handling of actions in the system.<br />
<span id="more-728"></span><br />
Read <a href="http://www.andygibson.net/blog/tutorial/getting-started-with-jsf-2-0-and-cdi-in-jee-6-part-1/">Part 1</a><br />
Read <a href="http://www.andygibson.net/blog/tutorial/getting-started-with-cdi-part-2-injection/">Part 2</a><br />
Read <a href="http://www.andygibson.net/blog/tutorial/getting-started-with-jsf-2-0-and-cdi-part-3/">Part 3</a></p>
<p>As a refresher, in our last part, we had an application that obtained a list of items, validated them and took a specific action when an invalid item was found. Lets say in the future we want to expand our system to handle all sorts of things happening when we find an invalid item. This could range from an email being sent, changes made to other data (i.e. an order canceled) or storing a list of rejections in a file or database table. To completely decouple the implementation we can use events. Events are raised by the event producer and subscribed to by event observers. Like most of CDI, event production and subscription is type safe and allows qualifiers to determine which events observers will observe.
</p>
<p>
Luckily we don&#8217;t have to change our application much to implement this, we just provide an implementation of the <code>ItemErrorHandler</code> that raises the event when it handles the item. We will inject an instance of the Item error handler called <code>EventErrorHandler</code> and create a <code>@Notify</code> qualifier to select it for injection.
</p>
<pre class="brush: java;">
@Retention(RetentionPolicy.RUNTIME)
@Target({FIELD,METHOD,PARAMETER,TYPE})
@Qualifier
public @interface Notify {}
</pre>
<pre class="brush: java;">
@Notify
public class EventItemHandler implements ItemErrorHandler {

    @Inject
    private Event&amp;lt;Item&amp;gt; itemEvent;

    public void handleItem(Item item) {
        System.out.println(&quot;Firing Event&quot;);
        itemEvent.fire(item);
    }
}
</pre>
<p>In this item handler, we inject an instance of an Event where the event payload will be an <code>Item</code>. The event payload is the state data passed from the event producer to the event observer which in this case passes the rejected Item. When the invalid item is handled, we fire the event and pass in the invalid item we received. This event based item handler is injected the same as any other item handler would be so we can swap it in and out whenever we need to and also can substitute it during testing.  We created a <code>@Notify</code> qualifier annotation to identify this error handler for injection and can use it in our item processor by adding it to the injection point.</p>
<pre class="brush: java;">
    @Inject
    @Notify
    private ItemErrorHandler itemErrorHandler;
</pre>
<p>If we deploy this now, we will see that when the item processor hits invalid items, the event based item error handler fires the event. Currently though we don&#8217;t have anything observing the event. We can fix this by creating an observer method which is the only thing needed to observe an event. We can still re-use our existing item processors by adding an event observer method to the implementations which just calls the error handler method. For example, to make our <code>FileErrorReporter</code> respond to the event, we add the following observer event.</p>
<pre class="brush: java;">
public class FileErrorReporter implements ItemErrorHandler,Serializable {

    public void eventFired(@Observes Item item) {
        handleItem(item);
    }
    ....
    ....
</pre>
<p>If you run the application now, you will see that the events are fired on the invalid objects, and the item information is being saved when this event is fired. You will also note that the lifecycle events are being observed. </p>
<pre class="brush: plain;">
INFO: Firing Event
INFO: Creating file error reporter
INFO: Saving eedemo.Item@1f84b46 [Value=34, Limit=7] to file
INFO: Closing file error reporter
INFO: Firing Event
INFO: Creating file error reporter
INFO: Saving eedemo.Item@2656da [Value=89, Limit=32] to file
INFO: Closing file error reporter
</pre>
<p>Note that the file error reporter bean is created each time the event is raised which may or may not be what we want. In this case, we don&#8217;t want to create the bean new each time since we don&#8217;t want to open and close the file for each item. We still want to open the file at the start of the process, and then close it once the process it completed. In this case, we need to consider the scope of the <code>FileErrorReporter</code> bean which doesn&#8217;t have a scope defined. When no scope is defined, CDI defaults it to the default pseudo dependent scope. What this means in practice is that the bean is created and destroyed over a very short space of time, typically over a method call. In our case here, the bean is created and destroyed for the duration of the event being fired. To fix this, we need to lengthen the scope of the bean by manually adding a scope annotation. We will make this bean <code>@RequestScoped</code> so once the bean is created the first time the event is fired, it will remain created for the duration of the request. Also, for any injection points that this bean is qualified to be injected to, the same bean instance will be injected. Here is the log when we make our scope change to the bean. Note that the bean is still only created when the event is fired. </p>
<pre class="brush: plain;">
INFO: Firing Event
INFO: Creating file error reporter
INFO: Saving eedemo.Item@1380c08 [Value=34, Limit=7] to file
INFO: Firing Event
INFO: Saving eedemo.Item@1b44f96 [Value=89, Limit=32] to file
INFO: Closing file error reporter
</pre>
<p>Let&#8217;s take the events example a little further. Right now we are observing any event for an item but chances are, there may be different types of events in the system for the items. We want to be specific in which observers subscribe to which events. Luckily CDI provides for this in a similar manner to how we determine suitable beans for injection points by using typing and qualifiers. </p>
<p>First, lets create a problem for ourselves by firing events off for each item we validate by adding the following code to the item processor.</p>
<pre class="brush: java;">
    @Inject
    private Event&amp;lt;Item&amp;gt; processorEvent;

    public void execute() {
        List&amp;lt;Item&amp;gt; items = itemDao.fetchItems();
        for (Item item : items) {
            processorEvent.fire(item);
            if (!itemValidator.isValid(item)) {
                itemErrorHandler.handleItem(item);
            }
        }
    }
</pre>
<p>This will fire an event for each item we process, but we don&#8217;t want the invalid item handler to subscribe to each of those events. If we do, we will see output like the following : </p>
<pre class="brush: plain;">
INFO: Creating eedemo.EventItemHandler_$$_javassist_748
INFO: Creating file error reporter
INFO: Saving eedemo.Item@6d0baf [Value=34, Limit=7] to file
INFO: Creating eedemo.EventItemHandler
INFO: Firing Event
INFO: Saving eedemo.Item@6d0baf [Value=34, Limit=7] to file
INFO: Saving eedemo.Item@1087300 [Value=4, Limit=37] to file
INFO: Saving eedemo.Item@11674c9 [Value=24, Limit=19] to file
INFO: Saving eedemo.Item@de163a [Value=89, Limit=32] to file
INFO: Firing Event
INFO: Saving eedemo.Item@de163a [Value=89, Limit=32] to file
INFO: Closing file error reporter
</pre>
<p>For each item, the file item handler observer is being called for each item because we aren&#8217;t distinguishing the kind of events fired when the item is processed and the kind of event fired when an invalid item is found. To differentiate between them we will create an <code>@Invalidate</code> qualifier to qualify the event for invalid items. This annotation will be placed on the event injection point and also on the observation point method. </p>
<pre class="brush: java;">
@Notify
@RequestScoped
public class EventItemHandler implements ItemErrorHandler {

    @Inject @Invalidated
    private Event&amp;lt;Item&amp;gt; itemEvent;

    public void handleItem(Item item) {
        System.out.println(&quot;Firing Event&quot;);
        itemEvent.fire(item);
    }
}
</pre>
<pre class="brush: java;">
@Save
@RequestScoped
public class FileErrorReporter implements ItemErrorHandler,Serializable {

    public void eventFired(@Observes @Invalidated Item item) {
        handleItem(item);
    }

    ....

}
</pre>
<p>If you run the code now, you will see that we no longer call the file save handler for each item, even though we are firing the event for each item.</p>
<pre class="brush: plain;">
INFO: Firing Event
INFO: Creating file error reporter
INFO: Saving eedemo.Item@1e3aa22 [Value=34, Limit=7] to file
INFO: Firing Event
INFO: Saving eedemo.Item@172940f [Value=89, Limit=32] to file
INFO: Closing file error reporter
</pre>
<p>You can add an event observer to the item processor just to see the events are still being raised and can be observed.</p>
<pre class="brush: java;">
@Named(&quot;itemProcessor&quot;)
@RequestScoped
public class ItemProcessor {

    ....

    public void observeItemEvent(@Observes Item item) {
        System.out.println(&quot;Item event observed for item &quot;+item);
    }
}
</pre>
<p>This will print a message whenever an event is fired so you can see that there is a difference between the two event subscribers and also that the more general version of the observer sees all events related to the item.</p>
<p>Events are a great way to decouple parts of the system in a modular fashion as you can add pieces that will subscribe to events with the event producer unaware of the observer as opposed to the even producer having to call the observer manually when events are not used. For example, if someone updates an order status, you could add events to email the sales rep, or notify an account manager if a tech support issue is open for more than a week. These kinds of rules can be implemented without events, but events make it easier to decouple the business logic. Additionally, there is no compile or build time dependency and you can just add modules to your application and they will automatically start observing and producing events. Additionally, observers and producers know nothing about each other, nor do they require any configuration for them to do so.</p>
<h4>Scheduling the Processing</h4>
<p>One last tidbit before we move on to creating CDI driven JSF apps is that for now we are running our code from a button in a JSF page but typically this is something that would get fired off on a regular basis. With the power of the EJB 3.1 scheduler we can do just that in a new class with few lines of code. We&#8217;ll create a new stateless EJB into which  we&#8217;ll inject our <code>ItemProcessor</code> and add a method to call the <code>execute()</code> method which will be called at a scheduled time.</p>
<pre class="brush: java;">
@Stateless
public class ScheduledProcessor {

    @Inject
    private ItemProcessor itemProcessor;

    @Schedule(hour=&quot;07&quot;,minute = &quot;00&quot;)
    public void execute() {
        System.out.println(&quot;executing scheduled job!&quot;);
        itemProcessor.execute();
    }
}
</pre>
<p>This makes use of the new EJB 3.1 <code>@Schedule</code> annotation and will schedule this method to be called every morning at 7am. You could make it on the hour every hour, or you could use the EJB timer service to implement your own timeout. We inject the same <code>ItemProcessor</code> implementation we have been using all along and call the <code>execute()</code> method. That is a pretty powerful transformation letting us re-use our existing code and easily incorporating EJB services with POJO managed beans into an EJB needing only a few lines of code.</p>
<p><small><b>Note</b> : If you actually implement this and run it, it won&#8217;t work because of a Weld 1.0 bug whereby the request scope isn&#8217;t active during calls to EJB timeouts (see <a href="https://jira.jboss.org/jira/browse/WELD-15">here</a> for details) so you&#8217;ll have to wait until Weld 1.01 which should be out fairly soon.</small></p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/tutorial/getting-started-with-jsf-2-0-and-cdi-part-3/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Getting Started with CDI part 2 &#8211; Injection</title>
		<link>http://www.andygibson.net/blog/tutorial/getting-started-with-cdi-part-2-injection/</link>
		<comments>http://www.andygibson.net/blog/tutorial/getting-started-with-cdi-part-2-injection/#comments</comments>
		<pubDate>Tue, 22 Dec 2009 13:45:20 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Netbeans]]></category>
		<category><![CDATA[Weld]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=706</guid>
		<description><![CDATA[In  part 1, we looked at creating a JEE 6 application with Netbeans using JSF and CDI running on Glassfish. Now we&#8217;ll take a closer look at using CDI for managing dependencies in a Java EE 6 environment.

Read Part 1
Read Part 2
Read Part 3
Last Time
Last time we looked at setting up the development environment [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://www.andygibson.net/blog/index.php/tutorial/getting-started-with-jsf-2-0-and-cdi-in-jee-6-part-1/"> part 1</a>, we looked at creating a JEE 6 application with Netbeans using JSF and CDI running on Glassfish. Now we&#8217;ll take a closer look at using CDI for managing dependencies in a Java EE 6 environment.<br />
<span id="more-706"></span><br />
Read <a href="http://www.andygibson.net/blog/tutorial/getting-started-with-jsf-2-0-and-cdi-in-jee-6-part-1/">Part 1</a><br />
Read <a href="http://www.andygibson.net/blog/tutorial/getting-started-with-cdi-part-2-injection/">Part 2</a><br />
Read <a href="http://www.andygibson.net/blog/tutorial/getting-started-with-jsf-2-0-and-cdi-part-3/">Part 3</a></p>
<h1>Last Time</h1>
<p>Last time we looked at setting up the development environment and creating our EE6 application in Netbeans and deploying it to Glassfish v3. This time, we&#8217;ll skip straight to writing code which can be put into either a new Netbeans project using the previous tutorial, or you can use the existing project and just add the new code.</p>
<h1>The &#8216;I&#8217; in CDI</h1>
<p>CDI is an API for injecting contexts and dependencies  which is the part we&#8217;ll turn our attention to now. In Seam and Spring dependencies worked mostly by naming beans and binding them to their injection points by their name. So far we have only referenced a managed bean by name from the JSF page when we defined the name for the bean using the <code>@Named</code> annotation. The primary role of the <code>@Named</code> annotation is to define the bean for the purpose of resolving EL statements within the application, usually through the JSF EL resolvers. Injection <i>could</i> be performed by using names, but this was not how injection in CDI was meant to work since CDI gives us a much richer way to express injection points and the beans to be injected into them.</p>
<p>Let&#8217;s look at an example which is somewhat contrived. We have a dao that returns a list of objects that need validating, and for invalid ones, we take a certain action.  Here&#8217;s the definition for the item.</p>
<pre class="brush: java;">
package eedemo;

public class Item {

    private int value;
    private int limit;

    @Override
    public String toString() {
        return super.toString() + String.format(&quot; [Value=%d, Limit=%d]&quot;, value,limit);
    }

    /*
    getters and setters omitted
    */
}
</pre>
<p>The <code>ItemDao</code> interface defines how we get the list of item objects. In this test application we anticipate using multiple implementations so we will code to interfaces. </p>
<pre class="brush: java;">
public interface ItemDao {

    List&lt;Item&gt; fetchItems();

}
</pre>
<p>The <code>ItemProcessor</code> is our main class that we will inject our beans into and execute the process from. For now, we will start with the Dao and look at how we will inject it into our processor bean.</p>
<pre class="brush: java;">
import java.util.List;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;

@Named(&quot;itemProcessor&quot;)
@RequestScoped
public class ItemProcessor {

    private ItemDao itemDao;

    public void execute() {
      List&lt;Item&gt;  items = itemDao.fetchItems();
      for (Item item : items) {
          System.out.println(&quot;Found item &quot;+item);
      }
    }
}
</pre>
<p>We&#8217;ll start with a simple Dao that just creates a list of items and returns a fixed list of items.</p>
<pre class="brush: java;">
public class DefaultItemDao implements ItemDao {

    public List&lt;Item&gt; fetchItems() {
        List&lt;Item&gt; results = new ArrayList&lt;Item&gt;();
        results.add(new Item(34, 7));
        results.add(new Item(4, 37));
        results.add(new Item(24, 19));
        results.add(new Item(89, 32));
        return results;
    }
}
</pre>
<p>In order to inject the <code>DefaultItemDao</code> into our <code>ItemProcessor</code> we add the <code>javax.inject.Inject</code> annotation to the <code>ItemDao</code> field to indicate that this field is an injection point.</p>
<pre class="brush: java;">
@Named(&quot;itemProcessor&quot;)
@RequestScoped
public class ItemProcessor {

    @Inject
    private ItemDao itemDao;

    ...
}
</pre>
<p>Finally, we need some way to call the <code>execute()</code< method on the <code>ItemProcessor</code>. We can run this in a SE environment, but for now we&#8217;ll keep it in a JSF page. We&#8217;ll add a new page with a button to call the execute method called <code>process.xhtml</code>.</p>
<pre class="brush: xml;">
&lt;?xml version='1.0' encoding='UTF-8' ?&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;
      xmlns:h=&quot;http://java.sun.com/jsf/html&quot;&gt;
    &lt;h:head&gt;
        &lt;title&gt;Item Processor&lt;/title&gt;
    &lt;/h:head&gt;
    &lt;h:body&gt;
        &lt;h:form&gt;
        &lt;h:commandButton action=&quot;#{itemProcessor.execute}&quot; value=&quot;Execute&quot;/&gt;&lt;br/&gt;
        &lt;/h:form&gt;
    &lt;/h:body&gt;
&lt;/html&gt;
</pre>
<p>If you open up the page at <a href="http://localhost:8080/ee6demo/faces/process.xhtml">http://localhost:8080/ee6demo/faces/process.xhtml</a> you will see just a button that when clicked lists the items from our default Dao implementation in the console.</p>
<pre class="brush: plain;">
INFO: Found item eedemo.Item@23cbc6 [Value=34, Limit=7]
INFO: Found item eedemo.Item@a40279 [Value=4, Limit=37]
INFO: Found item eedemo.Item@19e6292 [Value=24, Limit=19]
INFO: Found item eedemo.Item@1597bc4 [Value=89, Limit=32]
</pre>
<p>We created a class which implements the <code>ItemDao</code> interface and when the application was deployed our managed beans in the module were processed by the CDI implementation (again because of the <code>beans.xml</code> file in the module. Our <code>Inject</code> annotation specifies that we want to inject a managed bean into that field and the only thing we know about the bean to inject is that it must implement <code>ItemDao</code> or some subtype of that interface. In this case, the <code>DefaultItemDao</code> class fits the bill perfectly.</p>
<p>Let&#8217;s say we add another Dao class to our application which also implements the <code>ItemDao</code> interface, now the choice isn&#8217;t so clear as to which bean we want to inject.</p>
<pre class="brush: java;">
public class AnotherItemDao implements ItemDao {

    public List&lt;Item&gt; fetchItems() {
        List&lt;Item&gt; results = new ArrayList&lt;Item&gt;();
        results.add(new Item(99, 9));
        return results;
    }

}
</pre>
<p>We now have two classes the implement this interface and predictably, Weld gives us an ambiguous dependency error meaning that it cannot determine what bean to use for that injection point. Most, if not all of the errors that can occur with regards to CDI injection in Weld are reported at deployment time, even down to whether beans are missing a Serializable implementation.</p>
<pre class="brush: plain;">
Caused by: org.jboss.weld.DeploymentException: Injection point has ambiguous dependencies.
Injection point: field eedemo.ItemProcessor.itemDao; Qualifiers: [@javax.enterprise.inject.Default()]; 

Possible dependencies: [eedemo.AnotherItemDao, eedemo.DefaultItemDao]
</pre>
<p>We could make our <code>itemDao</code> field in the item processor a type that matches one of the implementation types (<code>AnotherItemDao</code> or  <code>DefaultItemDao</code>) since it would then match one and only one class type. However, then we would lose the benefits of coding to an interface and find it harder to change implementations without changing the field type. A better solution is to instead look at CDI Qualifiers.</p>
<h1>Qualifiers</h1>
<p>A CDI qualifier is an annotation that can be applied at the class level to indicate the kind of bean the class is, and also at the field level (among other places) to indicate what kind of bean needs to be injected at that point.</p>
<p>When CDI inspects an injection point to find a suitable bean to inject it takes not only the class type into account, but also any qualifiers. Without knowing it, we have already used one qualifier which is the default qualifier called <code>@Any</code>. Let&#8217;s create a <code>@Demo</code> qualifier which we can apply to our <code>DefaultItemDao</code> implementation and also to the injection point.</p>
<pre class="brush: java;">
package eedemo.qualifier;

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;

@Retention(RetentionPolicy.RUNTIME)
@Target({FIELD,METHOD,PARAMETER,TYPE})
@Qualifier
public @interface Demo {

}
</pre>
<p>First, we&#8217;ll add this qualifier to our default dao implementation at the class level.</p>
<pre class="brush: java;">
@Demo
public class DefaultItemDao implements SomeDao {

    public List&lt;Item&gt; fetchItems() {
..
..
</pre>
<p>If you save and deploy this file now, you may notice that we don&#8217;t have any errors, and if you go to the web page and click the execute button, you can see that in the console, it displays the list of items from the <code>AnotherItemDao</code> dao (remember we annotated the <code>DefaultItemDao</code> implementation but not the injection point). By adding the <code>Demo</code> qualifier to the default dao implementation, we made the other implementation a more suitable match for the injection point as it matched on type and on qualifiers and the <code>DefaultItemDao</code> has a qualifier that is not on the injection point making it less suitable.</p>
<p>If we add the <code>Demo</code> annotation to the injection point and deploy it, when we click our button we use the default implementation again. This is because we are matching based on type and qualifiers and the <code>DefaultItemDao</code> is the only bean with both the correct type and the <code>Demo</code> annotation.</p>
<h1>Alternative Injection Methods</h1>
<p>There are multiple ways to define an injection point on the injected class. So far we have annotated the fields that will reference the injected object. You do not need to provide getters and setters for field injection. If we wish to create immutable managed beans with final fields, we can use injection in the constructor by annotating the constructor with the <code>Inject</code> annotation. We can then apply any annotations to constructor parameters to qualify beans for injection (of course, each parameter has a type that can assist in qualifying beans for injection). A bean may only have one constructor with injection points defined, but it may implement more than one constructor.</p>
<pre class="brush: java;">
@Named(&quot;itemProcessor&quot;)
@RequestScoped
public class ItemProcessor {

    private final ItemDao itemDao;

    @Inject
    public ItemProcessor(@Demo ItemDao itemDao) {
        this.itemDao = itemDao;
    }
}
</pre>
<p>We can also call an inialization method which can be passed the beans to be injected.</p>
<pre class="brush: java;">
@Named(&quot;itemProcessor&quot;)
@RequestScoped
public class ItemProcessor {

    private ItemDao itemDao;

    @Inject
    public void setItemDao(@Demo ItemDao itemDao) {
        this.itemDao = itemDao;
    }
}
</pre>
<p>While in the above case we used the setter method for initialization we can create any method and use it for initialization with as many beans as we want in the method call. We can also have multiple initialization methods in a bean. </p>
<pre class="brush: java;">
    @Inject
    public void initBeans(@Demo ItemDao itemDao,@SomeQualifier SomeType someBean) {
        this.itemDao = itemDao;
        this.bean = someBean;
    }
</pre>
<p>The same rules apply to bean matching regardless of how the injection point is defined, it will try and find the best match based on type and qualifiers and will fail on deployment if there are multiple matching beans or no matching beans for an injection point.</p>
<p>Let&#8217;s look at the other aspects of our application, we get a list of items, iterate through them and test each one and if it fails that test, we pass it on to an error handler. We&#8217;ll create an <code>ItemValidator</code> interface to determines whether an item is valid or not.</p>
<pre class="brush: java;">
public interface ItemValidator {
    boolean isValid(Item item);
}
</pre>
<p>We&#8217;ll expand our <code>ItemProcessor</code> class to incorporate the new feature.</p>
<pre class="brush: java;">
@Named(&quot;itemProcessor&quot;)
@RequestScoped
public class ItemProcessor {

    @Inject @Demo
    private ItemDao itemDao;

    @Inject
    private ItemValidator itemValidator;

    public void execute() {
      List&lt;Item&gt;  items = itemDao.fetchItems();
      for (Item item : items) {
          System.out.println(&quot;Item = &quot;+item+&quot; valid = &quot;+itemValidator.isValid(item));
      }
    }
}
</pre>
<p>Our first implementation will be <code>DefaultItemValidator</code> which will simply test the limit against the value.</p>
<pre class="brush: java;">
public class DefaultItemValidator implements ItemValidator {

    public boolean isValid(Item item) {
        return item.getValue() &lt; item.getLimit();
    }
}
</pre>
<p>If we save our changes, go to our web page and click our button, in the console you will see that our items are being validated and the only valid item is where the value is less than the limit.</p>
<pre class="brush: plain;">
INFO: Item = eedemo.Item@25dd89 [Value=34, Limit=7] valid = false
INFO: Item = eedemo.Item@1f37ca2 [Value=4, Limit=37] valid = true
INFO: Item = eedemo.Item@7b8d67 [Value=24, Limit=19] valid = false
INFO: Item = eedemo.Item@18075da [Value=89, Limit=32] valid = false
</pre>
<p>Now lets consider the scenario where we have a deployment to a different site that is more relaxed and considers an item invalid only if the value is more than twice the limit. We may want to have another bean that implements the validator interface for that logic.</p>
<pre class="brush: java;">
public class RelaxedItemValidator implements ItemValidator {

    public boolean isValid(Item item) {
        return item.getValue() &lt; (item.getLimit() * 2);
    }
}
</pre>
<p>Now we have an ambiguous dependency problem since we have two classes implementing the same interface. The only difference is based on deployment so for most deployments, we want to use the default, but for one deployment, we want to use the relaxed implementation. CDI offers the use of the <code>Alternative</code> annotation which lets you package multiple beans that match an injection point without ambiguity errors, and the bean to use is defined in the <code>beans.xml</code>. This means you can deploy both implementations in the same module with the only difference being the beans.xml definition which can change over different deployments. </p>
<pre class="brush: java;">

@Alternative
public class DefaultItemValidator implements ItemValidator {

    public boolean isValid(Item item) {
        return item.getValue() &lt; item.getLimit();
    }
}
</pre>
<p>and</p>
<pre class="brush: java;">
@Alternative
public class RelaxedItemValidator implements ItemValidator {

    public boolean isValid(Item item) {
        return item.getValue() &lt; (item.getLimit() * 2);
    }
}
</pre>
<p>If we deploy our application now, we will get an unsatisfied dependency error since we defined the two matching beans as alternative but we didn&#8217;t enable either of them in the <code>beans.xml</code> file.</p>
<pre class="brush: xml;">
&lt;beans
    xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot;
    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
    xsi:schemaLocation=&quot;

http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/beans_1_0.xsd&quot;&gt;

    &lt;alternatives&gt;
        &lt;class&gt;eedemo.RelaxedItemValidator&lt;/class&gt;
    &lt;/alternatives&gt;
&lt;/beans&gt;
</pre>
<p>This tells CDI that for this deployment we want to use the <code>RelaxedItemValidator</code>. You can think of the alternative annotation as effectively disabling the bean making it unavailable for injection, but allowing the implementation to be packaged with the other beans. Adding it as an alternative in the <code>beans.xml</code> file effectively enables the bean making it available for injection. By moving this type of metadata to the <code>beans.xml</code> file, we can bundle different versions of the file with different deployments.</p>
<h1>Handling Invalid Items</h1>
<p>Continuing the example, invalid items are sent to the <code>ItemErrorHandler</code> as they are discovered.</p>
<pre name="code" class="java">
public interface ItemErrorHandler {
    void handleItem(Item item);
}
</pre>
<p>Let&#8217;s start by implementing a fake handler that saves the item details to a file. We want to open the file before we start handling items, leave it open for the duration of the process as we add content to the file, and then close the file when we are done with our processing. We could manually add <code>initProcess()</code> and <code>finishProcess()</code> methods to the error reporter bean, but then we couldn&#8217;t code to the interface since the caller would need to know about those class specific methods. We could add those same methods to the <code>ItemErrorReporter</code> interface but then we would have to unnecessarily implement those methods in every class that implements that interface. Instead, we can use some of the lifecycle annotations from the Managed Bean spec to call methods on the bean at certain points in the bean lifecycle. A <code>PostConstruct</code> annotated method is called when the bean has been constructed and any dependencies the bean has have been injected. Likewise, a <code>PreDestroy</code> annotated method is called just before the bean is disposed of by the container.</p>
<pre class="brush: java;">
public class FileErrorReporter implements ItemErrorHandler {

    @PostConstruct
    public void init() {
        System.out.println(&quot;Creating file error reporter&quot;);
    }

 @PreDestroy
    public void release() {
        System.out.println(&quot;Closing file error reporter&quot;);
    }

    public void handleItem(Item item) {
        System.out.println(&quot;Saving &quot;+item+&quot; to file&quot;);
    }
}
</pre>
<p>Our final change is to add the item error handling into our <code>ItemProcessor</code> bean.</p>
<pre class="brush: java;">
@Named(&quot;itemProcessor&quot;)
@RequestScoped
public class ItemProcessor {

    @Inject @Demo
    private ItemDao itemDao;

    @Inject
    private ItemValidator itemValidator;

    @Inject
    private ItemErrorHandler itemErrorHandler;

    public void execute() {
      List&lt;Item&gt;  items = itemDao.fetchItems();
      for (Item item : items) {
          if (!itemValidator.isValid(item)) {
              itemErrorHandler.handleItem(item);
          }
      }
    }
}
</pre>
<p>When we run this from our browser we see the following in the console ;</p>
<pre class="brush: plain;">
INFO: Creating file error reporter
INFO: Saving eedemo.Item@d8b01e [Value=34, Limit=7] to file
INFO: Saving eedemo.Item@12a5e8 [Value=89, Limit=32] to file
INFO: Closing file error reporter
</pre>
<h1>Next Time</h1>
<p>Different application deployments might use different rules for handling invalid items. such as rejecting the item, to sending notifications to individuals or just flagging them or listing them in an output file. In addition, we may want to do a combination of these (reject an order, send email to the sales rep, and list it in a file).<br />
One great way to handle this kind of multi-faceted problem is using events which we&#8217;ll look at next time.</p>
<p>Click to view <a href="http://www.andygibson.net/blog/tutorial/getting-started-with-jsf-2-0-and-cdi-part-3/">getting started with jsf 2.0 and CDI part 3</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/tutorial/getting-started-with-cdi-part-2-injection/feed/</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
		<item>
		<title>Getting Started with JSF 2.0 and CDI in JEE 6 part 1</title>
		<link>http://www.andygibson.net/blog/tutorial/getting-started-with-jsf-2-0-and-cdi-in-jee-6-part-1/</link>
		<comments>http://www.andygibson.net/blog/tutorial/getting-started-with-jsf-2-0-and-cdi-in-jee-6-part-1/#comments</comments>
		<pubDate>Wed, 16 Dec 2009 14:20:03 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Netbeans]]></category>
		<category><![CDATA[Weld]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=647</guid>
		<description><![CDATA[Here&#8217;s a quick tutorial on how easy it is to get started with JSF 2.0 and JSR 299, Java Contexts and Dependency Inject (CDI) using the latest release of Netbeans 6.8.

Read Part 1
Read Part 2
Read Part 3
Getting Netbeans and JEE6
First download the latest version of Netbeans (at the time of writing 6.8 has just been [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a quick tutorial on how easy it is to get started with JSF 2.0 and JSR 299, Java Contexts and Dependency Inject (CDI) using the latest release of Netbeans 6.8.<br />
<span id="more-647"></span><br />
Read <a href="http://www.andygibson.net/blog/tutorial/getting-started-with-jsf-2-0-and-cdi-in-jee-6-part-1/">Part 1</a><br />
Read <a href="http://www.andygibson.net/blog/tutorial/getting-started-with-cdi-part-2-injection/">Part 2</a><br />
Read <a href="http://www.andygibson.net/blog/tutorial/getting-started-with-jsf-2-0-and-cdi-part-3/">Part 3</a></p>
<h1>Getting Netbeans and JEE6</h1>
<p>First download the latest version of Netbeans (at the time of writing 6.8 has just been released). Make sure the download version you choose includes Glassfish V3 and java web and EE. Once downloaded, install it and get it up and running and we can start writing the application.</p>
<h1>Starting the Project</h1>
<p>Once Netbeans is up and running, start a new web project by clicking New Project and select the Java Web category and select a Web Application project and click next.</p>
<p>Give the new project a name (I called mine ee6demo) and a directory and click next. On the server settings, Glassfish v3 should already be selected so select next. In this tab, make sure Java Server Faces is selected and stick with the defaults in the lower panel that appears when you select it.</p>
<p>You can now click finish and Netbeans will create the project and open it up for you in the IDE. On the left you can see the project explorer and in the main tab you can see a file called index.html. Without doing anything, open the Run menu in the main menu and select &#8220;Run Main Project&#8221;. After a moment of activity and console logging a web browser window should open up with the message &#8220;Hello From Facelets&#8221; which is exactly what we can see in the index.xhtml file. So far, we haven&#8217;t done anything and we already have a working web application shell.</p>
<p>Just take a moment and look at the tabs on the left hand side, you should see Project,Files, and Services. Click on the services tab and expand the Servers node and you should see the Glassfish server we are using with a little green arrow on it indicating that the server is running. For now, we don&#8217;t need this because we aren&#8217;t actually going to deploy to the server again, no restarts and no manual deployments, so go back to the projects tab on the left.</p>
<h1>Adding some code</h1>
<p>In the projects tab, expand the &#8220;Source Packages&#8221; node and right click and select New->Java Class. Give the class the name <code>MessageServerBean</code> and a package name (I used <code>eedemo</code>). We annotate the class with the <code>javax.inject.Named</code> annotation and a single method to return a string.</p>
<pre class="brush: java;">
package eedemo;

import javax.inject.Named;

@Named
public class MessageServerBean {

    public String getMessage() {
        return &quot;Hello World!&quot;;
    }
}
</pre>
<p>This a managed bean as defined by CDI which in Glassfish v3 is implemented using Weld from JBoss. One thing we need to do now is tell the server that this project is a module containing CDI beans. We add a file called <code>beans.xml</code> to the project in the WEB-INF folder. Right click on the WEB-INF folder in the project manager in the ee6Demo/Web Pages/folder and select New->XML Document. In the file name editor, just call it <code>beans</code>, <b>not</b> <code>beans.xml</code> as the IDE will add the xml extension for you and if you add the xml extension, the file will be called <code>beans.xml.xml</code> (I&#8217;ve often tripped myself up with that one!). Open the beans.xml file in the editor, and select all the text and delete it so it is an empty file.  You could alternatively just put <code><beans></beans></code>. (<b>Note</b> This file can be used to specify bean related information in xml so you aren&#8217;t limited to annotations)</p>
<p>The last change is to edit the <code>index.xhtml</code> and replace the &#8220;Hello From Facelets&#8221; with our own text.</p>
<pre class="brush: xml;">
        Message is : #{messageServerBean.message}&lt;br/&gt;
        Message Server Bean is : #{messageServerBean}
</pre>
<p>Save it and go to your browser and refresh the page (<code><a href="http://localhost:8080/ee6demo/">http://localhost:8080/ee6demo/</a></code>). </p>
<p>Message is : Hello World!<br />
Message Server Bean is : eedemo.MessageServerBean@xxxxxxx </p>
<p>You should now see the message from the bean displayed on the page. Now go back into your message bean and change the message to something else (I used <code>Hello From Weld!</code>), save the file and then refresh the browser. Your new message appears automatically since your application code has been hot deployed automatically by Netbeans . If you don&#8217;t see your changes just give it a second and refresh again.</p>
<p>From the second line in our page you can see that the class name is <code>eedemo.MessageServerBean</code> and the bean is just a pojo. Even though this is JEE, there is no complex class hierarchy wrapped in layers of transactions, interceptors and all that &#8216;Heavy&#8217; stuff you keep hearing about. </p>
<h1>What&#8217;s going on?</h1>
<p>When the application is deployed, the presence of a <code>beans.xml</code> file signals that this module contains CDI managed beans so the classes on the path are scanned for CDI annotations. Our bean was annotated with the <code>@Named</code> annotation and so this class was registered with Weld (under that name) (<b>edit</b> in a CDI module, all beans are registered with Weld, the named annotation is just used to match beans to injection points). When our JSF page was rendered, JSF tried to resolve the value of <code>messageServerBean</code> in the page using the registered expression resolvers in JSF. One of these is the Weld EL Resolver which has the MessageServerBean class registered under the name <code>messageServerBean</code>. We could have specified a name with the annotation, but since we didn&#8217;t it was registered under the default name of the class name with a lower case first name. The Weld resolver returns an instance of this bean in response to the request from JSF. Bean naming is only needed when using EL expressions and should not be used as the default mechanism for injection. CDI provides type safe injection by class type and stereotypes or qualifiers as we&#8217;ll see later.</p>
<h1>Upgrading to an EJB</h1>
<p>As we are using a JEE stack, we can easily deploy our bean as an EJB with some small changes thanks to EJB 3.1. Just open up the <code>MessageServerBean</code> and add the <code>javax.ejb.Stateless</code> annotation at the class level. Again, just save the file and go to your browser and refresh (no manual deploying, just save the file), and you should see something like :</p>
<p>Message is : Hello From Weld!<br />
Message Server Bean is : eedemo.__EJB31_Generated__MessageServerBean__Intf____Bean__@xxxxxxx </p>
<p>Amazingly, we turned our pojo bean into a fully featured EJB with just one annotation, we saved it, and refreshed our page and our changes appeared, we don&#8217;t have to create any weird project configurations, local interfaces or arcane deployment descriptors.  </p>
<h1>Different EJB types</h1>
<p>You can also try using the <code>@Stateful</code> annotation (don&#8217;t forget to implement the <code>java.io.Serializable</code> interface in the bean as it needs to be able to passivate (<b>edit</b> This isn&#8217;t necessary for it to be an EJB, but it is necessary if you want it to be session or conversation scoped)). Alternatively, you could try the new <code>@Singleton</code> annotation for singleton instances. If you do, you may notice that there is a <code>javax.ejb.Singleton</code> and <code>javax.inject.Singleton</code>. Why two Singleton annotations? A single annotation in CDI lets you define a singleton instance outside of EJB in case you are using CDI in a non-EJB environment. An EJB singleton will have all the features of an EJB such as transaction management so you have the choice depending on your needs and whether the environment is EJB or not.</p>
<p>In this first part, we have created a new JSF 2.0 application, made it CDI enabled and added a managed bean which we then referenced from the web page. In part 2, we&#8217;ll start looking at creating more complex beans and injecting them into and with other beans.</p>
<p>Click to view <a href="http://www.andygibson.net/blog/index.php/2009/12/22/getting-started-with-cdi-part-2-injection/">Part 2</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/tutorial/getting-started-with-jsf-2-0-and-cdi-in-jee-6-part-1/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
		<item>
		<title>Java EE 6 Is Here</title>
		<link>http://www.andygibson.net/blog/news/java-ee-6-is-here/</link>
		<comments>http://www.andygibson.net/blog/news/java-ee-6-is-here/#comments</comments>
		<pubDate>Fri, 11 Dec 2009 00:13:19 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[Glassfish]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Netbeans]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=689</guid>
		<description><![CDATA[Like Christmas come early, Sun announced the release of JEE 6. This release sees continued improvement in the JEE stack with the inclusion of JSR 299, Java Contexts and Dependency Injection (CDI), and EJB 3.1 as well as JSF 2.0, and JPA 2.0. JSF especially has seen changes as a result of practical user feedback [...]]]></description>
			<content:encoded><![CDATA[<p>Like Christmas come early, Sun <a href="http://www.sun.com/aboutsun/pr/2009-12/sunflash.20091210.1.xml">announced</a> the release of JEE 6. This release sees continued improvement in the JEE stack with the inclusion of JSR 299, Java Contexts and Dependency Injection (CDI), and EJB 3.1 as well as JSF 2.0, and JPA 2.0. JSF especially has seen changes as a result of practical user feedback and community add-ons such as Seam and JSF Ajax frameworks which have contributed back to the JCP.</p>
<p>Glassfish v3 which implements the full JEE 6 stack has also been released, with JBoss&#8217; Weld as the CDI implementation. Netbeans 6.8 has also been released with full JEE 6 project support including maven support for enterprise applications. Also of note is the hot deploy function of Glassfish which can deploy your app while maintaining session information.</p>
<p>Personally, I&#8217;m pleased. JEE 6 has really improved things for the java standards, and CDI has filled some gaps that previously required different additional pieces to completely fill. The ghosts of EJB 2.1 should now be permanently laid to rest, but should serve as a stark reminder. Having good frameworks to build standards based solutions is always good for the community.</p>
<p>I&#8217;ll try and get some tutorials on developing with CDI and JSF 2.0 with Netbeans and Glassfish out soon.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/news/java-ee-6-is-here/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Seam is Dead, Long live Seam</title>
		<link>http://www.andygibson.net/blog/article/seam-is-dead-long-live-seam/</link>
		<comments>http://www.andygibson.net/blog/article/seam-is-dead-long-live-seam/#comments</comments>
		<pubDate>Thu, 03 Dec 2009 13:39:30 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[Seam]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=637</guid>
		<description><![CDATA[With Weld 1.0, the reference implementation of JSR 299 &#8211; Java Contexts and Dependency Injection now released, attention at JBoss has no doubt turned to Seam 3 which is going to be built on top of Weld. Red Hat and JBoss are committed to returning innovations back the JCP as is the case with Seam [...]]]></description>
			<content:encoded><![CDATA[<p>With Weld 1.0, the reference implementation of JSR 299 &#8211; Java Contexts and Dependency Injection now released, attention at JBoss has no doubt turned to Seam 3 which is going to be built on top of Weld. Red Hat and JBoss are committed to returning innovations back the JCP as is the case with Seam which not only resulted in JSR 299, but has also influenced a number of other JSRs especially JSF 2. With JSR 299 standardizing the Seam &#8217;style&#8217; of development it also brings about a some fundamental game changes for Seam 3 (hence the title) as much of the strength of Seam becomes part of the JEE standards.<br />
<span id="more-637"></span><br />
One problem I have with Seam is the all-or-nothing level of intrusion it has. I&#8217;m either working on a Seam app, or I&#8217;m not, and I pretty much have to commit to it at the start of the project. One thing Spring had going for it was you didn&#8217;t need to commit to it initially. You could start your web app, and then just add in a little bit of Spring at a time. You could continue adding Spring until it is littered all the way through your code.</p>
<p>Developers can be finnicky at times, and find topics such as heavy app servers and framework lock-in (even to the standards) to be more of an issue than they should be. On this level, Seam really lost out since it was based on standards, ran on an app server (although it ran in many environments), and there was a degree of lock-in as a Seam project, not much more than any other framework based project.</p>
<p>However, Seam itself is an excellent framework and it certainly helped make JSF 1.2 a more usuable framework. Most of those holes are now patched permanently with JSF 2.0 which logically would mean that JSF 2.0 is up to par with JSF 1.2 plus Seam. Well, not quite, although JSF has come a long way I think the one reason Seam soothed a lot of pains was not just down to the fact that it made JSF 1.2 usable. It was also because of the additional functionality it provided above and beyond the average web framework. First was the conversation scope which not only provided a more versatile scope than request and session scope, but also laid the foundation for resolving other problems. With conversation scope we are able to easily handle multiple browser windows/tabs, including independent page flows within those tabs as well as providing Workspace management. Second, it was a full stack solution with a (softly) predefined set of libraries providing different pieces of the stack. No more piecing together different technologies and getting it to work properly, you got everything in one bundle to create stateful rich web applications.</p>
<p>There are probably interesting times ahead for Seam with the evolution of JEE 6 and the release of CDI. EJB 3.1 continues the trend of making EJBs easier than ever, JSF 2.0 makes it a more pleasant experience (now with AJAX), and Weld now provides us not only with a standards based, contextual dependency injection framework, and also makes conversational applications possible out of the box. Many of the great things Seam offered is now available in JEE 6 as part of a standard stack. This is an exciting prospect for developers and makes the JEE 6 stack far more attractive, but doesn&#8217;t it also reduce the need for Seam?</p>
<p>JEE 6 isn&#8217;t simply Seam standardized, nor is it even Seam lite. There are still a number of larger features in Seam not available in JEE and rightfully so since there are a number of functions which are too specific to be standardized. This particularly applies to the features that span across multiple technologies that fit into neither the CDI, JPA, or JSF libraries. Interestingly, the Seam name would also still be suitable as a framework used to stitched them all together which was originally the concept for Seam. JSR 299 offers not only a firm base onto which you can implement those features, but allows implementing them as expansion plugins to the CDI framework through which most of Seam 3 will be implemented.</p>
<p>My hope is that Seam 3 will consist of a set of fairly independent plugins that can be added to applications in the form of CDI / JSF plugins so there is less lock-in and more of a sense of adding Seam where it is needed. This way we don&#8217;t need to start with a Seam application from the start, we can start with a standard plain old JEE 6 web application using EJB, CDI, JSF, JPA and add the Seam features as needed. Another benefit here is that when we add Seam components in such a manner, we are not adding framework code, we are adding features that works on top of our existing framework since the base code for such features is already in the JEE stack. This has worked well in the past on various different platforms, specifically in Java with JSF and the different component libraries available for it.  I think this softer approach to integration will make it more appealing in the long run, . While JEE 6 may have lower barriers to entry for this functionality, JBoss have shown they are able to compete in such environments, for example on the JSF front they have previously competed with different stateful and conversational frameworks.</p>
<p>Overall, things are looking very interesting for the future of JEE 6, and its progress has sparked a resurgent interest from developers. JSR 299 fills an important gap in JEE giving developers a powerful and feature filled standard web stack which can be extended easily. While it may remove some of the need for Seam, it also offers more opportunities for Seam to integrate with the new stack effortlessly and build on it with more features.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/seam-is-dead-long-live-seam/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Glassfish, Netbeans and JSF 2.0 Test Drive</title>
		<link>http://www.andygibson.net/blog/article/glassfish-netbeans-and-jsf-2-0-test-drive/</link>
		<comments>http://www.andygibson.net/blog/article/glassfish-netbeans-and-jsf-2-0-test-drive/#comments</comments>
		<pubDate>Tue, 03 Nov 2009 04:32:44 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Netbeans]]></category>
		<category><![CDATA[Seam]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=611</guid>
		<description><![CDATA[I&#8217;ve spent some time in the last couple of weeks playing around with Glassfish, Netbeans 6.8 Beta (and milestone 2 before it) and JSF 2.0, and I have to say that this is turning out to be a really good set of development libraries and tools.

(note This post relates to both the milestone 2 and [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve spent some time in the last couple of weeks playing around with Glassfish, Netbeans 6.8 Beta (and milestone 2 before it) and JSF 2.0, and I have to say that this is turning out to be a really good set of development libraries and tools.<br />
<span id="more-611"></span></p>
<p>(<b>note</b> This post relates to both the milestone 2 and beta versions of Netbeans 6.8 which I have been tinkering with over the duration of this article being written.)</p>
<p>The <a href="http://www.netbeans.org/community/releases/68/">download for Netbeans 6.8 </a> comes with <a href="https://glassfish.dev.java.net/">Glassfish v3 </a> which implements JEE 6 including <a href="http://jcp.org/en/jsr/detail?id=314">JSF 2.0</a> and <a href="http://jcp.org/en/jsr/detail?id=317">JPA 2.0</a>.</p>
<p>Glassfish now has <b>really</b> fast hot deployment so you can change a line of code, save it, and it re-deploys instantly which in my opinion, this is a huge productivity booster. This isn&#8217;t limited to Netbeans, the eclipse plugins also provide this feature, and it works with pretty much any framework. I tried it with Wicket and Spring MVC and it was fantastic to get a wicket error where I had forgotten to add a component, so I go back to the java page code, add the component, refresh my browser and it works. Glassfish now has support for JEE 6 so you can make a pojo a local EJB just by adding the <code>@stateless</code> annotation to it. You can also deploy EJBs in war files as well without needing the whole EAR setup. One problem I did see was that when you used the EAR project setup with an EJB and War project, the hot deploy didn&#8217;t appear to work as well. Changes to the war file didn&#8217;t appear to redeploy, maybe because it is the EAR file that is deployed and not the war. However, still fantastic stuff.</p>
<p>Netbeans 6.8 beta was released in the last week or so. Feature-wise it is a great product with better tooling for JSF, including JSF 2.0, facelets support, and auto-completion for JSF backing beans in the JSF page. It also includes support for JEE 6, EJB 3.1, JPA 2.0 and development with Glassfish v3. It also improves upon the existing Maven support by providing for mavenized Ear projects. </p>
<p>While the features are impressive, Netbeans still seems hindered by performance issues and some minor bugs (although it is a milestone/beta release). Personally, I found this release no more sluggish that other releases although some people in the forums have had worse experiences. Netbeans strength has always been that it offers one standard solution without the plugin nightmares that eclipse has. While Netbeans has plugins they are more like installable features, they have a higher granularity than Eclipse plugins which is more like DLL hell. That said, I use Eclipse at work and it is always hard to shift from one keyboard mapping to another, and Eclipse does seem faster without the intermittent pauses. However, right now, Netbeans is a superior product in terms of features, especially for a JSF developer. I&#8217;d keep an eye out for the 6.8 final release to see how it comes out, and give 6.8 milestone 2 a go just to enjoy the experience if you are interested in using a standards based stack because thats obviously where the Netbeans folks are focused. </p>
<p>One big issue I have with Netbeans is the oddness of some of the key mappings. I think in nearly every application I use I press Alt+F and then C to close the currently edited document. Whether is it in MS Office, Borland Delphi, Eclipse, Firefox, while in the file menu, the C key always closes the currently open document you are editing. In Netbeans, it closes the currently edited project which means suddenly my project disappears when I want to close an edited file. Another is the use of Ctrl+Space for invoking auto completion which in Netbeans sends focus to the project manager or something like that. Sure, I can change the keymappings, such as to the Eclipse profile, but then I&#8217;m using some arbitrary weird key mapping which isn&#8217;t Netbeans and it isn&#8217;t completely the same as Eclipse. It is probably this way for legacy reasons, but some of these key presses are de facto standards.</p>
<p>Lastly, we come to JSF 2.0 which was forged from JSF 1.2 and the litany of complaints about it. The JSR group looked at the solutions out in the wild that already work around those problems (many of which were written by people in that very group) and incorporates those fixes in a standard JSF API type of way. Primarily we have the dropping of JSP as the default view in exchange for the Facelets / JSF templating solution. This also lent itself very well to easier component creation including no-code components. There is now zero configuration required except for the servlet in <code>web.xml</code> and managed beans can now be defined using annotations. Navigation which also used to be in the <code>faces-config.xml</code> is also more convention of configuration. Another big request was the inclusion of AJAX awareness in the JSF lifecycle . It provides the bare minimum features that 3rd party developers can build upon using the standard API instead of their own AJAX solutions. There is better support for GET requests and page parameters as well as invoking actions on page requests which is a feature often used in Seam.<br />
There is also some performance boosts with regards to re-working state saving and the resource access mechanisms have been improved a great deal.</p>
<p>Also noteworthy is the inclusion of <a href="http://www.seamframework.org/Weld">Weld CR 1</a> which is the reference implementation of <a href="http://jcp.org/en/jsr/detail?id=299"> JSR 299 &#8211; Java Contexts and Dependency Injection </a> from JBoss. Admittedly, I haven&#8217;t really gotten round to taking a look at it, but from what I have seen and read so far, it looks like it fills some gaps in the JEE 6 platform and is up to par with the new found simplicity and strength that JEE 6 is promoting right now.</p>
<p>Overall, this is a pretty exciting set of tools and framworks and well worth a look if you are interested in adopting a standards based stack. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/glassfish-netbeans-and-jsf-2-0-test-drive/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Notes On Choosing A Web Framework</title>
		<link>http://www.andygibson.net/blog/article/notes-on-choosing-a-web-framework/</link>
		<comments>http://www.andygibson.net/blog/article/notes-on-choosing-a-web-framework/#comments</comments>
		<pubDate>Fri, 25 Sep 2009 13:24:47 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Seam]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Wicket]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=549</guid>
		<description><![CDATA[I&#8217;m looking at starting a new project and once again find myself choosing between frameworks. Having spent some time evaluating different ones I wrote up some notes to share and get some feedback that might alter my thoughts or opinions. Here&#8217;s the criteria I&#8217;m using to choose a framework in no particular order.

IDE Support &#8211; [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m looking at starting a new project and once again find myself choosing between frameworks. Having spent some time evaluating different ones I wrote up some notes to share and get some feedback that might alter my thoughts or opinions. Here&#8217;s the criteria I&#8217;m using to choose a framework in no particular order.<br />
<span id="more-549"></span></p>
<p><strong>IDE Support</strong> &#8211; I would like to get as much IDE support as possible for auto completion, code validation and general helpfulness.</p>
<p><strong>Resume Building</strong> &#8211; How much demand is there for the skills? I&#8217;m looking to bolster my skills that have wide adoption in the industry. As this is an important factor, it also means I probably won&#8217;t be choosing a framework that I am already very familiar with. I&#8217;ll be using job trends and opinion to determine the industry support for the frameworks. I know job sites aren&#8217;t the best measure, especially since many ads are stuffed with buzzwords so they appear in searches even if there is no JSF, JAXB or JAX-WS involved. However, the fact that they are included at all indicates some kind of market penetration of the technology.</p>
<p><strong>Ajax Support</strong> &#8211; How well does it support Ajax natively out of the box as opposed to requiring third party libraries and are there de-facto standard libraries for that framework if they are needed.</p>
<p><strong>Templating / Layout</strong> &#8211; How are pages built and organized to enable reusable HTML without using include statements everywhere or some other mechanism which will require every page to be edited if the layout is changed. I think facelets is the best page layout library out there as it pulls the template into the page and then pushes the content from the page into the template making separate files optional. Tiles requires separate definition files and does a similar thing outside of the page being rendered. Sitemesh is non invasive and works by decorating existing pages as they are sent to the client. In terms of writing actual pages, the choices are Jsp, Velocity and Freemarker, of which JSP and Velocity are the two most in demand.</p>
<p><strong>Completeness</strong> &#8211; How much is in the framework out of the box without requiring additional libraries for core functionality. Obviously, you are going to need libraries for things like data access, but the framework should be able to put text in a page without requiring third party libraries. One other aspect of this is how easy it is to get up and running without having to get different pieces configured and talking to each other. Some frameworks discussed here like Spring MVC and JSF are not meant to be complete frameworks but a framework onto which to build other frameworks (like Servlets). In these cases, the frameworks are expanded by third party libraries so completeness is not so much a factor here. Third party libraries integrated as part of the stack is acceptable (i.e. Sitemesh in Grails and Richfaces in Seam).</p>
<p><strong>Custom Paginated Tables with Sortable Columns</strong> &#8211; This is my barrier for determining how powerful and easy a framework is to use. Simple CRUD is trivial to write, it&#8217;s like hello world for the web so I usually go for a more robust litmus test by writing some pagination code. Action frameworks require you to chug all the parameters backwards and forwards and handle your own binding and determining whether a page was selected or next/previous was clicked while Component frameworks handle most of that for you. For the same reason, clickable columns can be a real pain. For bonus points, how easy is it to implement multiple paginated / sortable tables? </p>
<p><strong>Statefulness</strong> &#8211; Can we integrate some kind of stateful mechanism in there (i.e Spring Web Flow) cleanly? There are a few scenarios where I will need a stateful workflow in the application.</p>
<p><strong>Third Party Support and integration</strong> &#8211; One annoying aspect of java web development is all the pieces and parts that need to be strung together and then you have to get them to play nicely. This is really about the path of least surprise, and not having to deal with issues because I add libraries that don&#8217;t have special mechanisms for working with each other.. I.e Spring MVC embraces Tiles, but how much of a hassle is it to incorporate Velocity with Tiles? This issue is also somewhat redundant for those frameworks that include built-in solutions for most needs. </p>
<p>The application is going to be moderate in size, but hopefully growing as time goes on. For that reason, I&#8217;m looking for something flexible enough to grow and refactor later on. Initially, I&#8217;m also looking for something lightweight and will be looking to deploy it on Tomcat primarily due to ease of hosting. </p>
<h1>Action or Component Based</h1>
<p>I find Action frameworks are great for catalogs and simple CRUD pages but when you start getting to more complex web applications pages, things get much tricker. Take for example a search page with 10 search parameters, suddenly you find yourself having to attach 10 parameters to the next/previous/first/last result links or using javascript funkiness to modify form contents to change the form state and post the form. Add column ordering and things get pretty messy quickly. In my mind, For a web application, any search pages (or other pages that require pagination or other common interface elements) should be trivial to write within minutes. Obviously, if you are Google and your main business is that one search page, you can afford to spend a little more time on it and be as choosy as you like on how to implement it. However, it never fails to amaze how much code people will write to create a single page demonstrating how to do some simple function in a non-reusable way. User interface elements like pagination and column ordering should be totally reusable. </p>
<h1>The Contenders</h1>
<p>Here are the contenders in no specific order</p>
<ul>
<li>Seam with JSF</li>
<li>Wicket</li>
<li>JSF</li>
<li>Grails</li>
<li>Spring MVC with JSP</li>
<li>Spring MVC with JSF</li>
</ul>
<p>First lets look at the job trends for these different frameworks :</p>
<div style="width:540px">
<a href="http://www.indeed.com/jobtrends?q=spring+java%2C+ejb+java%2C+jsf+java%2C+%22spring+mvc%22+java%2C+wicket+java%2C+seam+java%2C+grails+java" title="spring java, ejb java, jsf java, &#034;spring mvc&#034; java, wicket java, seam java, grails java Job Trends"><br />
<img width="540" height="300" src="http://www.indeed.com/trendgraph/jobgraph.png?q=spring+java%2C+ejb+java%2C+jsf+java%2C+%22spring+mvc%22+java%2C+wicket+java%2C+seam+java%2C+grails+java" border="0" alt="spring java, ejb java, jsf java, &#034;spring mvc&#034; java, wicket java, seam java, grails java Job Trends graph"><br />
</a></p>
<table width="100%" cellpadding="6" cellspacing="0" border="0" style="font-size:80%">
<tr>
<td><a href="http://www.indeed.com/jobtrends?q=spring+java%2C+ejb+java%2C+jsf+java%2C+%22spring+mvc%22+java%2C+wicket+java%2C+seam+java%2C+grails+java">spring java, ejb java, jsf java, &#034;spring mvc&#034; java, wicket java, seam java, grails java Job Trends</a></td>
<td align="right"><a href="http://www.indeed.com/q-spring-java-jobs.html">spring java jobs</a> &#8211; <a href="http://www.indeed.com/q-ejb-java-jobs.html">ejb java jobs</a> &#8211; <a href="http://www.indeed.com/q-jsf-java-jobs.html">jsf java jobs</a> &#8211; <a href="http://www.indeed.com/jobs?q=%22spring+mvc%22+java">&#034;spring mvc&#034; java jobs</a> &#8211; <a href="http://www.indeed.com/q-wicket-java-jobs.html">wicket java jobs</a> &#8211; <a href="http://www.indeed.com/q-seam-java-jobs.html">seam java jobs</a> &#8211; <a href="http://www.indeed.com/q-grails-java-jobs.html">grails java jobs</a></td>
</tr>
</table>
</div>
<p>We can see a sort of multi-tier system in place for different frameworks. Spring and EJB both rank up there as first tier technologies. I&#8217;ve already had quite a bit of experience with both of these but Spring is at an advantage with regards to being lightweight and running in tomcat without having to worry about setting up an embedded EJB container. Writing something with EJB 6 might be a possibility, but I think it more likely I&#8217;ll try and use Spring.</p>
<p>Now lets consider the view frameworks :</p>
<div style="width:540px">
<a href="http://www.indeed.com/jobtrends?q=+jsf+java%2C+%22spring+mvc%22+java%2C+wicket+java%2C+seam+java%2C+grails+java" title="jsf java, &#034;spring mvc&#034; java, wicket java, seam java, grails java Job Trends"><br />
<img width="540" height="300" src="http://www.indeed.com/trendgraph/jobgraph.png?q=+jsf+java%2C+%22spring+mvc%22+java%2C+wicket+java%2C+seam+java%2C+grails+java" border="0" alt="jsf java, &#034;spring mvc&#034; java, wicket java, seam java, grails java Job Trends graph"><br />
</a></p>
<table width="100%" cellpadding="6" cellspacing="0" border="0" style="font-size:80%">
<tr>
<td><a href="http://www.indeed.com/jobtrends?q=+jsf+java%2C+%22spring+mvc%22+java%2C+wicket+java%2C+seam+java%2C+grails+java">jsf java, &#034;spring mvc&#034; java, wicket java, seam java, grails java Job Trends</a></td>
<td align="right"><a href="http://www.indeed.com/q-jsf-java-jobs.html">jsf java jobs</a> &#8211; <a href="http://www.indeed.com/jobs?q=%22spring+mvc%22+java">&#034;spring mvc&#034; java jobs</a> &#8211; <a href="http://www.indeed.com/q-wicket-java-jobs.html">wicket java jobs</a> &#8211; <a href="http://www.indeed.com/q-seam-java-jobs.html">seam java jobs</a> &#8211; <a href="http://www.indeed.com/q-grails-java-jobs.html">grails java jobs</a></td>
</tr>
</table>
</div>
<h1>Seam / JSF</h1>
<p>I&#8217;ve had a lot of experience with these two so it&#8217;s easy to comment on. Great IDE support (probably the best), great out of the box support, but it can feel foreign to use on Tomcat where it doesn&#8217;t offer such a rich a developer experience. Great Ajax support, but not so great for the resume since I already have a lot of experience with Seam and there are very few Seam jobs out there.</p>
<table style="width: 100%; font-size: 90%">
<tr>
<th colspan=4>Seam</th>
</tr>
<tr>
<td><strong>IDE Support</strong></td>
<td>Excellent &#8211; JBoss Tools</td>
<td><strong>Demand</strong></td>
<td>Poor</td>
</tr>
<tr>
<td><strong>Ajax Support</strong></td>
<td>Excellent &#8211; Richfaces</td>
<td><strong>Templating</strong></td>
<td>Excellent &#8211; Facelets</td>
</tr>
<tr>
<td><strong>Pagination</strong></td>
<td>Excellent &#8211; reusable component based pagination</td>
<td><strong>Completeness</strong></td>
<td>Excellent</td>
</tr>
<tr>
<td><strong>Statefullness</strong></td>
<td>Excellent &#8211; Conversational scope</td>
<td><strong>3rd Party Library Integration</strong></td>
<td>Ok &#8211; Seam likes things to run a certain way</td>
</tr>
</table>
<h1>JSF</h1>
<p>Despite using Seam a lot, writing a straight JSF application is still quite different and poses a number of challenges. It might be a interesting using just JSF but I have most of that ground covered with my existing JSF work. JSF is in-demand though and this might be an opportunity to use it with other frameworks such as a Spring/Hibernate/JSF combination. It has great Ajax support with multiple frameworks available, but no decent IDE support even though JBoss Tools works well on plain JSF apps without Seam. It may also get frustrating since I&#8217;ll be having constant reminders of how easy things are when you use Seam. Facelets is a great templating framework, if not the best, and I&#8217;d probably go to JSF 2.0 so I can use annotated beans. For statefulness, I could add in Orchestra and pagination should be simple with JSF although I think Seam (or JBoss-El) added ways to call methods (with parameters) on beans passed in to facelets which made it really easy. I haven&#8217;t been able to duplicate that with in JSF or Spring Faces which could be a problem. One annoyance of JSF is the inability to suppress validation when you post the form back but don&#8217;t want to save it which you may want to do as part of a web flow where you want to save the contents, go to another page, come back and finish your data entry. The only solution is to manually perform validation when the form is finally saved and not use JSF validators which is a limitation and I don&#8217;t thing this was fixed in JSF 2.0.</p>
<table style="width: 100%; font-size: 90%">
<tr>
<th colspan=4>JSF</th>
</tr>
<tr>
<td><strong>IDE Support</strong></td>
<td>Ok with JBoss Tools</td>
<td><strong>Demand</strong></td>
<td>Excellent</td>
</tr>
<tr>
<td><strong>Ajax Support</strong></td>
<td>Great with 3rd Party tools or JSF 2.0</td>
<td><strong>Templating</strong></td>
<td>Excellent &#8211; Facelets</td>
</tr>
<tr>
<td><strong>Pagination</strong></td>
<td>Good</td>
<td><strong>Completeness</strong></td>
<td>Ground framework</td>
</tr>
<tr>
<td><strong>Statefulness</strong></td>
<td>None without 3rd party libs like Apache Orchestra</td>
<td><strong>3rd Party Library Integration</strong></td>
<td>Excellent for JSF libs</td>
</tr>
</table>
<h1>Wicket</h1>
<p>Wicket is a great component based framework with good ajax support, a fine grained stateful architecture and because of it&#8217;s emphasis on the java language, good IDE support. Some people don&#8217;t like the heavy use of java code to build web pages, but it&#8217;s a personal thing and I do enjoy it. However, the only thing holding it back for me is the poor industry adoption with very few Wicket jobs. </p>
<table style="width: 100%; font-size: 90%">
<tr>
<th colspan=4>Wicket</th>
</tr>
<tr>
<td><strong>IDE Support</strong></td>
<td>Great since it is mostly java based</td>
<td><strong>Demand</strong></td>
<td>Poor &#8211; unfortunately</td>
</tr>
<tr>
<td><strong>Ajax Support</strong></td>
<td>Excellent &#8211; it comes with Ajaxified components</td>
<td><strong>Templating</strong></td>
<td>Excellent &#8211; Offers page inheritance and panels</td>
</tr>
<tr>
<td><strong>Pagination</strong></td>
<td>Excellent &#8211; reusable component based pagination</td>
<td><strong>Completeness</strong></td>
<td>Good</td>
</tr>
<tr>
<td><strong>Statefullness</strong></td>
<td>Excellent &#8211; Fine grained statefulness</td>
<td><strong>3rd Party Library Integration</strong></td>
<td>Great &#8211; although you won&#8217;t need or be able to use many web libraries (i.e. tiles, velocity etc) here.</td>
</tr>
</table>
<h1>Grails</h1>
<p>I tried to get back into Grails and again, I hit a number of snags. It&#8217;s a great framework, but I find it can be problematic. The IDE support was basic and I often had to clean the eclipse project then the grails project so it wouldn&#8217;t choke on old classes lying around. Netbeans also has Grails support, but was prone to hanging when you want to restart the server. It also lacked the refactoring / renaming features present in eclipse.  I also found problems in the framework itself such as not being able to model embedded classes that contained a reference to another entity. Other times, inexplicably, when I called <code>person.save()</code> nothing would happen, no error, no messages, nothing. I don&#8217;t doubt it was my fault and something I did, but it is off putting and frustrating in a framework that won&#8217;t tell you when you have a syntax error.</p>
<p>Grails and Wicket seem like polar opposites in some ways. Wicket is all about type safety and strict java code checked by the IDE. Grails on the other hand doesn&#8217;t often know when you make a mistake because its a dynamic language.  Developers shouldn&#8217;t have to write tests just to make sure you didn&#8217;t make any typo&#8217;s in your classes, people have spent a number of years and millions of dollars evolving IDEs to solve that very problem.</p>
<p>The dynamic language is all very nice, and Grails is a framework but when I&#8217;m building furniture, I don&#8217;t start out with aflat pack plywood cabinet and slowly replace each piece with half inch mahogany with hand cut dovetail joints in the name of being rapid and agile (umm, Agile Wordworking, there&#8217;s an idea). I can see the point, and for the most part, Grails is unobtrusive but I think for me,  on this project, I&#8217;d rather start out with a workbench and some planks of mahogany and craft it from scratch. </p>
<p>Ajax support is excellent and it also has many plugins which are easy to install and use. Writing taglibs is a breeze and very intuitive. Even pagination was fairly simple and I especially liked the paginator tag that takes a map of parameter values to include on all the previous/next/page links. Again, things are scarce on the job front for Grails, but being such a unique and productive tool I think there is a great future for Grails which lowers the importance of current trends. </p>
<p>Grails also supports Spring Web Flow but I&#8217;m not sure it allows the use of flow scoped persistence contexts. Sitemesh is used for templating and offers a lot of features out of the box. Overall it&#8217;s very impressive and definitely still a contender.</p>
<table style="width: 100%; font-size: 90%">
<tr>
<th colspan=4>Grails</th>
</tr>
<tr>
<td><strong>IDE Support</strong></td>
<td>Poor</td>
<td><strong>Demand</strong></td>
<td>Small but growing</td>
</tr>
<tr>
<td><strong>Ajax Support</strong></td>
<td>Excellent</td>
<td><strong>Templating</strong></td>
<td>Excellent &#8211; Sitemesh and easy taglibs</td>
</tr>
<tr>
<td><strong>Pagination</strong></td>
<td>Great</td>
<td><strong>Completeness</strong></td>
<td>Great &#8211; plugins make things easier</td>
</tr>
<tr>
<td><strong>statefulness</strong></td>
<td>Spring Web Flow </td>
<td><strong>3rd Party Library Integration</strong></td>
<td>Plugins make it really easy</td>
</tr>
</table>
<h1>Spring MVC with JSP</h1>
<p>This is probably the one I was most eager to tackle as I think this one probably has the most potential. Spring and JSP have been largely adopted within the industry, but are they any good? I think Spring MVC is excellent, especially with the new Spring 2.5 Controller annotations and Web Flow integration. As usual with Spring, it provides a lot of flexibility and it sits on the Core Spring Framework. For templating, I can use Sitemesh, Tiles, and it includes support for velocity and free marker. It appears that using both Tiles and Velocity together isn&#8217;t straightforward resulting in this third party <a href="http://anydoby.com/velocity/">plugin</a> to solve the problem.</p>
<p>Spring MVC doesn&#8217;t have any ajax support, <a href="http://static.springsource.org/spring/docs/2.0.x/reference/mvc.html">Chapter 13 &#8211; Web MVC Framework</a> of the Spring reference documentaton doesn&#8217;t even mention the word Ajax. Spring Web Flow has Ajax support but it requires the use of Tiles (or some other compatible templating library) for specifying page fragments to update. This is also requires that pages be designed in such a way that the Ajax updatable pieces are clearly defined in the page definition which is outside of the page being designed. With Richfaces you can create a fragment in the page just by using an output panel tag and giving it a name. Another problem with Spring Web Flow is the inability to use an Open Session In View alongside the Flow Managed Persistence context which means having to work around Lazy Initialization Issues in other ways. On the plus side though, you can make validation optional in Spring Web Flow if you are using the Spring Validators and not JSF.</p>
<table style="width : 100%;font-size : 90%">
<tr>
<th colspan=4>Spring MVC with JSP </th>
</tr>
<tr>
<td><strong>IDE Support</strong></td>
<td>Good &#8211; Spring IDE</td>
<td><strong>Demand</strong></td>
<td>Excellent</td>
</tr>
<tr>
<td><strong>Ajax Support</strong></td>
<td>Poor</td>
<td><strong>Templating</strong></td>
<td>3rd Party</td>
</tr>
<tr>
<td><strong>Pagination</strong></td>
<td>Roll Your Own</td>
<td><strong>Completeness</strong></td>
<td>Spring MVC offers a solid ground on which to build</td>
</tr>
<tr>
<td><strong>statefulness</strong></td>
<td>Spring Web Flow</td>
<td><strong>3rd Party Library Integration</strong></td>
<td>Good</td>
</tr>
</table>
<h1>Spring MVC with JSF / Spring Faces</h1>
<p>If I couldn&#8217;t find a way to reconcile the problems with Spring MVC and JSP, this would be my backup as it solves a number of problems with using Spring MVC and JSP. It fixes the Ajax and templating issues since I can use a JSF based Ajax framework (IceFaces or Richfaces) and Facelets for superior templating. The only problems here is a resource issue for JSF and the fact that I have already worked with JSF extensively. However, I have found Spring Faces to be a great library to use with some nice extensions. While there are only a few jobs explicitly mentioning Spring Faces, there are many jobs involving Spring and JSF. While spring web flow de-couples your view from the back end, it can be a little too decoupled. For example, within a flow, to call a method from a command button and refresh some data requires you to call the method and return an action string that would trigger the refresh of the data in the web flow. In Seam, you can get away with just calling the method and then refreshing the data. Spring Web Flow, forces you to decouple that which makes for a lot more work when you have multiple links that can trigger a refresh of the data. It also doesn&#8217;t fix the open session in view / flow managed persistence context clash. Writing JSF pages outside of a web flow means having to work directly with Spring beans as Jsf backing beans as opposed to dealing with Spring Beans through the web flow. This isn&#8217;t a big deal though, it just means you have two separate styles of writing code.  Even though Spring Web Flow lets you suppress validations for flow transitions, It doesn&#8217;t have any effect when you are using JSF for the view, only when you are using Spring validations.</p>
<table style="width: 100%; font-size: 90%">
<tr>
<th colspan=4>Spring MVC with JSF / Spring Faces</th>
</tr>
<tr>
<td><strong>IDE Support</strong></td>
<td>Good &#8211; JBoss Tools for JSF and Spring IDE</td>
<td><strong>Demand</strong></td>
<td>Great &#8211; Spring and JSF Combination</td>
</tr>
<tr>
<td><strong>Ajax Support</strong></td>
<td>Excellent</td>
<td><strong>Templating</strong></td>
<td>Excellent &#8211; Facelets</td>
</tr>
<tr>
<td><strong>Pagination</strong></td>
<td>Good</td>
<td><strong>Completeness</strong></td>
<td>Good</td>
</tr>
<tr>
<td><strong>statefulness</strong></td>
<td>Soring Web Flow</td>
<td><strong>3rd Party Library Integration</strong></td>
<td>Good</td>
</tr>
</table>
<h1>Summary</h1>
<p>Ultimately, it boils down to Grails or Spring MVC with JSP and probably Tiles and if I can&#8217;t find a solution there, Spring MVC with JSF. I f career/employment was not a factor, I would pick Wicket with Spring in a second, however, as I&#8217;m looking to bolster my resume and make sure my bona fides are in order for the more popular technologies.</p>
<p>All in all, it&#8217;s a difficult choice, but I&#8217;d love to get some more thoughts on the matter. I&#8217;m sure there are plenty of opinions on frameworks out there in The java community <img src='http://www.andygibson.net/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /><br />
<script type="text/javascript">var dzone_url = 'http://www.andygibson.net/blog/index.php/2009/09/25/notes-on-choosing-a-web-framework/';</script><br />
<script type="text/javascript">var dzone_title = 'Notes On Choosing A Web Framework';</script><br />
<script type="text/javascript">var dzone_blurb = 'Yet another write up of my ongoing evaluation of different web frameworks for a new Java project';</script><br />
<script type="text/javascript">var dzone_style = '1';</script><br />
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/notes-on-choosing-a-web-framework/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Java Standards Redux &#8211; Spring Licensing Fallout</title>
		<link>http://www.andygibson.net/blog/article/java-standards-redux-spring-licensing-fallout/</link>
		<comments>http://www.andygibson.net/blog/article/java-standards-redux-spring-licensing-fallout/#comments</comments>
		<pubDate>Fri, 03 Oct 2008 17:00:08 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=70</guid>
		<description><![CDATA[In this post I talked about how the Java standards are important to ensuring java has a long and fruitful life. This post references Spring as an example but was written before the fallout from the Spring licensing issues. This fallout tends to back up the argument that standards are important, although since there were [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://www.andygibson.net/blog/index.php/2008/09/30/why-java-focus-on-the-standards/">this post</a> I talked about how the Java standards are important to ensuring java has a long and fruitful life. This post references Spring as an example but was written before the fallout from the Spring licensing issues. This fallout tends to back up the argument that standards are important, although since there were no standards at the time for Spring to follow, it is not a totally valid position.<br />
Over the years, many people have been knocked for claiming that Spring is a proprietary framework. How can it be when it is open source would often be the argument. Proprietary in its literal sense means that it has one owner or controller which is true for Spring for the most part. A less formal definition when discussing programming, Java in particular, is that it does not follow any open standards. Spring broke a lot of new ground which in many cases, meant that there were no standards or only bad standards to follow. However, a number of developers also bought into using other Spring features like the Templates to aid them in their development.<br />
Now that Spring has penetrated developers code to a large degree, vendor lock in was in place for many companies with large spring based projects and Rod and Co turned off the free beer once everyone was hooked. Again, it&#8217;s their business, their platform, and they can do with it as they like.<br />
However, if the Java platform had a set of good standards for defining framework functions, then nobody would seriously bother with a non-standard framework, and nobody would be able to shut off the tap because they could be replaced in an instant by an alternative implementation of the standard. Again, this reinforces the need for good standards (like EJB3.1 appears to be) and also for timely updates to the standards. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/java-standards-redux-spring-licensing-fallout/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Is Spring between the devil and the EJB?</title>
		<link>http://www.andygibson.net/blog/article/is-spring-between-the-devil-and-the-ejb/</link>
		<comments>http://www.andygibson.net/blog/article/is-spring-between-the-devil-and-the-ejb/#comments</comments>
		<pubDate>Thu, 28 Aug 2008 05:51:47 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=11</guid>
		<description><![CDATA[Reading this post on Javalobby prompted me to go and dust off a post I wrote a while ago but hadn?t published regarding Spring and the revitalized EJB standard. At the time I was fired up by this post by Rod Johnson which seemed to be a large helping of FUD and insults. Nonsense such [...]]]></description>
			<content:encoded><![CDATA[<p>Reading <a title="this post" href="http://java.dzone.com/articles/ejb-30-and-spring-25" target="_blank">this post</a> on <a title="javalobby" href="http://www.javalobby.org" target="_blank">Javalobby</a> prompted me to go and dust off a post I wrote a while ago but hadn?t published regarding Spring and the revitalized EJB standard. At the time I was fired up by <a href="http://blog.springsource.com/main/2008/04/09/the-biggest-losers-next-contestant-java-bloatware/" target="_blank">this post</a> by Rod Johnson which seemed to be a large helping of FUD and insults. Nonsense such as suggesting that because some people were using app servers and some weren?t the age of the app server was over, like suggesting that because I want a shovel to dig a hole, we no longer need backhoes. This was interspersed with some irrelevant quotes from Gartner made to look like evidence and malicious comments about EJBs and their users. It seemed like the Spring folks were chomping at the bit to pronounce EJB dead when in fact, as evidenced by some recent posts, it is very much alive. In hindsight, it seems the Spring guys were trying to lay some marketing groundwork prior to releasing their own OSGI application server.</p>
<p>This brings me to this latest post, one of a number of recent posts which sings the praises of EJBs and in this case asks the Spring developer &#8220;why not?&#8221;. It&#8217;s almost like the question nobody asks because the presumption is that the answer is obvious. It also touches on the issue of Spring and EJB developers not getting along which I think in part was fueled by the old arguments of Rod and Gavin who seem &#8216;passionate&#8217; about their technology choices. However, there is still some animosity between the two camps years after those minor flame wars.  I think part of it stems from the normal response of users being defensive, and therefore offensive or protective of their technology of choice because of flaws they are aware off even if they disagree with them, which is a normal response.</p>
<p><strong>Disclaimer</strong> : I&#8217;m currently working on a Seam project and have been involved on the Seam forums. However, when I need a quick dependency injection library (especially for SE), I turn to Spring.</p>
<p>EJB users are having to defend a technology which has the appearance of being stodgy and has a terrible legacy even though its modern day incarnation is far more hip, cool and even Spring-like. Few negative comments about EJBs appear to be about flaws in the current implementation other than the fact that EJBs require a container.</p>
<p>The Spring users have to defend a technology that is in essence proprietary as opposed to standards based, and while the core Spring functionality (DI, AOP) is very good, a number of people believe that it is starting to spread itself a little too thin, and starting to suffer from the dreaded ?Bloat?. It is now facing competition from EJB, a technology that is not only as easy to use and powerful but is also a standard, which, all things being equal, is a positive. If nothing else, being a standard will also give it a helping hand in being adopted in some of the more corporate shops.</p>
<p>While SpringSource haven?t implemented the standards, I?m sure there will be a Spring driven implementation of Web Beans (JSR 299) which could drag Spring kicking and screaming under the standards umbrella. If Web Beans gains traction and becomes the accepted way of defining components for web applications, then there is a chance people will choose the standards based web beans syntax over a proprietary Spring syntax and be able to swap out implementations. One advantage Spring does have is the ability to provide its core functionality on both desktop and web applications which unfortunately, isn?t a part of the Web Beans spec (yet?). This may provide enough reason for developers to avoid using Web Beans or at least limit it to pieces that will definitely be web based only.</p>
<p>I do like the fact that the only opaque part of Spring is the container. Other pieces like the transaction manager, data sources and so on are all transparent for you to see in your configuration unlike the EJB container where they are just bundled in and magically mess with your beans. This lack of apparent simplicity can also be a turn off for some people who prefer a simpler Spring solution over complex old EJBs.</p>
<p>In some ways Spring feels like that small cafe that worked really well, was cheap and served great food compared to &#8216;those chains&#8217;. They decide to open a couple more restaurants up, and the owner can&#8217;t run all of them so he hires extra help, and trains them, but they don&#8217;t always get it right, and lack the enthusiasm with personal service. He opens a couple more stores up and decides to produce a manual detailing every aspect of the recipes and customer service. Before he knows it, he is one of &#8216;those chains&#8217;, and the quality of food has gone down, and the prices have gone up. Not that I think every Spring project is prone to fail unless it is under the guiding hand of Rod. However, Spring has spread beyond it&#8217;s core functionality and expecting the same level of buy-in from developers, and from Rod&#8217;s post referenced at the beginning of this post, it seems they are even trying to Manufacture buy-in.</p>
<p>At one time, the Spring team would have criticized the inability to move a &#8217;standard&#8217; EJB  from one app server to another, now they just expect you to deploy applications in their proprietary modules for their app server. They would have criticized the bloat of the implemented standards, and now if you want to use their web flow API, you have to include their Web MVC framework even if you are using JSF. I think this is a bit of a reach from the SpringSource folks. Just because I put my Dependency Injection egg in your basket, it doesn&#8217;t automatically mean I&#8217;m going to put my view technology and server choice eggs in there too.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/is-spring-between-the-devil-and-the-ejb/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
