<?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; JSF</title>
	<atom:link href="http://www.andygibson.net/blog/tag/jsf/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>Accessing and Paginating CSV Files with DataValve</title>
		<link>http://www.andygibson.net/blog/tutorial/accessing-and-paginating-csv-files-with-datavalve/</link>
		<comments>http://www.andygibson.net/blog/tutorial/accessing-and-paginating-csv-files-with-datavalve/#comments</comments>
		<pubDate>Wed, 28 Jul 2010 17:07:30 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Apprentice]]></category>
		<category><![CDATA[CSV]]></category>
		<category><![CDATA[DataValve]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Swing]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1123</guid>
		<description><![CDATA[
 Prerequisites
Install Maven
Installing DataValve Into Maven


While DataValve is mostly used with database driven back ends, this tutorial shows you how DataValve can turn a comma delimited file into a paginated list of objects that the user can page through. We will then use this data provider in a console application, a Swing application and a [...]]]></description>
			<content:encoded><![CDATA[<div class="prereq floatRight">
<ul> <lh>Prerequisites</lh></p>
<li>Install Maven</li>
<li><a href="http://www.andygibson.net/blog/tutorial/install-datavalve-into-maven/">Installing DataValve Into Maven</a></li>
</ul>
</div>
<p>While <a href="http://www.andygibson.net/blog/projects/datavalve/">DataValve</a> is mostly used with database driven back ends, this tutorial shows you how DataValve can turn a comma delimited file into a paginated list of objects that the user can page through. We will then use this data provider in a console application, a Swing application and a JSF web page using the DataValve data client interfaces.<br />
 <span id="more-1123"></span><br />
We will start by writing this tutorial as a console application and then demonstrate how the data provider can be used in other applications, even web applications. We&#8217;ll start by creating a new Maven application and then include the dependencies for DataValve. We&#8217;ll then create our comma delimited data provider, define a row mapper class for it, and hook it up to our demo data. We&#8217;ll then attach it to a dataset so we can easily iterate through the data. We will then take our provider and use it in different clients.</p>
<ol>
<li>Create a new Maven application in your IDE and add <code>datavalve-dataset</code>  as a dependency in your <code>pom.xml</code> file.
<pre class="brush: xml;">
	&lt;dependencies&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.fluttercode.datavalve&lt;/groupId&gt;
			&lt;artifactId&gt;datavalve-dataset&lt;/artifactId&gt;
			&lt;version&gt;0.9.0.CR2&lt;/version&gt;
		&lt;/dependency&gt;
	&lt;/dependencies&gt;
</pre>
</li>
<li>Create a new class called <code>Person</code> in the package of your choice. I used <code>org.fluttercode.tutorials.datavalve.csvreader</code> We will only be using one package in this demonstration.</li>
<li>The <code>Person</code> class will be our model which will be populated from the comma delimited file.
<pre class="brush: java;">
public class Person {

	private Integer id;
	private String firstName;
	private String middleName;
	private String lastName;
	private Date dob;
	private String email;
	private String address;
	private String city;
	private String zip;

	public Person() {
	}

	public Person(Integer id, String firstName, String lastName,String middleName,
			Date dob, String email, String address,
			String city, String zip) {
		super();
		this.id = id;
		this.firstName = firstName;
		this.middleName = middleName;
		this.lastName = lastName;
		this.email = email;
		this.dob = dob;
		this.address = address;
		this.city = city;
		this.zip = zip;
	}

	public String getName() {
		return firstName + &quot; &quot; + lastName;
	}

	public String getAddressText() {
		return address+ &quot;,&quot; + city+&quot;,&quot;+zip;
	}

	@Override
	public String toString() {
		return String.format(&quot;Person [id=%d, name=%s, dob=%s,address=%s, email=%s&quot;,
		    id,getName(),dob,getAddressText(),email);
	}

    .... Getters and Setters Omitted ....
}
</pre>
</li>
<li>In order to convert the csv data to an object, we need to create a <code>ColumnarRowMapper</code> instance. This takes a row of data, already converted to an array of string values, builds the model object from it and returns it back to the caller. Create a new class called <code>PersonRowMapper</code>.</li>
<pre class="brush: java;">
public class PersonRowMapper implements ColumnarRowMapper&lt;Person&gt; {

    private static SimpleDateFormat converter = new SimpleDateFormat(
			&quot;MM/dd/yyyy&quot;);

	public Person mapRow(String[] values) {
		Date dob = null;

		try {
			dob = converter.parse(values[5]);
		} catch (ParseException e) {
		}

		return new Person(DataConverter.getInteger(values[0]), values[1],
				values[2], values[3], dob, values[4], values[6], values[7],
				values[8]);
	}
}
</pre>
<p>This row mapper implements the <code>ColumnarRowMapper</code> interface and implements the single method to return a built entity object from the array of column values passed in.</p>
<li>The only other element we need is some test data to run it on which you can download from <a href='http://www.andygibson.net/blog/wp-content/uploads/2010/07/data.zip'>here</a>. Download this file and place it in the package folder with your source code. Depending on your IDE, you may need to refresh the folder in the package explorer so it can pick up the new file in the folder. The example file has 100 rows of data in it.</li>
<li>Create a new class called <code>ProviderFactory</code> which will create our provider and initialize it with the CSV file url.
<pre class="brush: java;">
public class ProviderFactory {

	public static CommaDelimitedProvider&lt;Person&gt; createProvider() {
		URL url = ProviderFactory.class.getResource(&quot;data.csv&quot;);
		CommaDelimitedProvider&lt;Person&gt; provider;
		provider = new CommaDelimitedProvider&lt;Person&gt;(url.getFile());
		provider.setRowMapper(new PersonRowMapper());
		return provider;
	}
}
</pre>
<p>We use a <code>URL</code> to reference the csv file stored in the jar from which we get a <code>File</code> instance that we can pass to our <code>CommaDelimitedProvider</code>. This relies on the <code>data.csv</code> file being in the same location as this class. Alternatively, you can put the file elsewhere and just create a regular <code>File</code> object to it rather than use the <code>URL</code>.
</li>
<li>For the console part of this demo, create a <code>Main</code> class and add a <code>main</code> method containing the code get an instance of the provider, and perform a simple iteration through the data.
<pre class="brush: java;">
public class Main {

	public static void main(String[] args) {
		CommaDelimitedProvider&lt;Person&gt; provider;

		provider= ProviderFactory.createProvider();

		List&lt;Person&gt; results = provider.fetchResults(new DefaultPaginator());
		for (Person p : results) {
			System.out.println(p);
		}
	}
}
</pre>
<p>In this example we are reading all the results at once in memory and displaying the whole list.</li>
</ol>
<h2>Paginating the results</h2>
<p>We can control which results and how many are displayed by using a paginator to control the flow of data. This can be useful if you have a huge file and it would be impractical to read all the results into memory in one go. Datasets have paginators built in and use a reference to a provider to fetch the actual data.</p>
<ol>
<li>In the <code>main</code> method, instead of using the provider directly, create a dataset and pass it a reference to our data provider.
<pre class="brush: java;">
public static void main(String[] args) {
	CommaDelimitedProvider&lt;Person&gt; provider;

	provider = ProviderFactory.createProvider();

	CommaDelimitedDataset&lt;Person&gt; ds = new CommaDelimitedDataset&lt;Person&gt;(provider);
	ds.setMaxRows(10);
	List&lt;Person&gt; results = ds.getResultList();
	for (Person p : results) {
		System.out.println(p);
	}
}
</pre>
<p>We have set the maximum number of rows to 10 so the results returned only contains 10 rows of data at most. We can use this mechanism to control the number of results fetched if they are paginated.</li>
<li>The dataset classes implement the <code>Iterable</code> interface which lets us iterate over the entire set of data. By setting the page size, we can control the batch sizes when the data is fetched in while it is being iterated over. This allows us to control the flow of data, either to reduce the in-memory realization of the source data, or to reduce latency in an otherwise slow data source as the application can process one page of data while the provider is loading the next page of data.
<pre class="brush: java;">
public static void main(String[] args)  {
	CommaDelimitedProvider&lt;Person&gt; provider;
	provider = ProviderFactory.createProvider();

	CommaDelimitedDataset&lt;Person&gt; ds = new CommaDelimitedDataset&lt;Person&gt;(provider);
	ds.setMaxRows(5);
	for (Person p : ds) {
		System.out.println(p);
	}
}
</pre>
</li>
<li>You can see this process in action by extending the comma delimited data provider as an anonymous class and adding logging to the post fetch methods. We do this by modifying the <code>ProviderFactory.createProvider()</code> method :
<pre class="brush: java;">
public static CommaDelimitedProvider&lt;Person&gt; createProvider() {
	URL url = Main.class.getResource(&quot;data.csv&quot;);
	CommaDelimitedProvider&lt;Person&gt; provider = new CommaDelimitedProvider&lt;Person&gt;(url.getFile()) {
		@Override
		protected List&lt;Person&gt; doPostFetchResults(List&lt;Person&gt; results,
				Paginator paginator) {
			int end = paginator.getFirstResult()+paginator.getMaxRows();
			System.out.println(&quot;Fetching results from &quot;+paginator.getFirstResult()+&quot; to &quot;+end);
			return results;
		}
	};
	provider.setRowMapper(new PersonRowMapper());
	return provider;
}
</pre>
</li>
<li>
If you run this now, with the max rows set to 5, in you will see in that log that we iterate through all the records, but we only fetch the results every 5 rows since the max results is set to 5.</p>
<pre class="brush: plain;">
Fetching results from 0 to 5
Person [id=6825, name=JUANITA LAMBERT, address=139 MANNING HWY,CLYO,76604, email=mbeasley@everyma1l.biz
Person [id=5740, name=GREG CABRERA, address=736 GENESSEE BLVD,CORDELE,17433, email=cholder@b1zmail.biz
Person [id=8599, name=ALISSA WISE, address=205 ALICE RD,CAMILLA,14855, email=theyweb@eyec0de.net
Person [id=9282, name=SHARON WINTERS, address=955 COHEN PIKE,TYRONE,811, email=jlogan@hotma1l.com
Person [id=2150, name=KRISTY FRANKS, address=1471 ALEXIS PKWY,BALDWIN,85, email=jgates3@somema1l.com
Fetching results from 5 to 10
Person [id=9927, name=JEFF RICE, address=104 DUNDEE PKWY,HOGANSVILLE,3741, email=diedlots@b1zmail.org
Person [id=7972, name=TAMARA BRYANT, address=1382 WOGAN BLVD,CITY OF CALHOUN,43790, email=hotworn@everyma1l.us
Person [id=5824, name=ALISHA YANG, address=716 HOGANS DR,HARDING,58932, email=foundwrong@hotma1l.net
Person [id=3402, name=JASON NGUYEN, address=527 MICHAEL CRES,FORT STEWART,14664, email=haveothers@ma1l2u.com
Person [id=3620, name=LINDSEY CABRERA, address=1420 LAZELERE HTS,FORT STEWART,21650, email=askeddreams@b1zmail.com
Fetching results from 10 to 15
Person [id=3511, name=ANTHONY MATHEWS, address=1325 OKEY LN,THUNDERBOLT,63656, email=cfarrell@everyma1l.co.uk
Person [id=572, name=JARED FORD, address=722 EUCLID RD,FORSYTH,42014, email=ortrying@b1zmail.co.uk
Person [id=9720, name=AUTUMN WILLIAMS, address=260 HILL PARK,NORCROSS,58355, email=roomwhere@hotma1l.net
Person [id=3447, name=MARION BROWN, address=739 MIDDLE PATH,MACON,9944, email=hwagner@b1zmail.co.uk
Person [id=9356, name=HOPE HAYNES, address=1023 COOPERRIDERS CRES,STATENVILLE,34247, email=sacrificeit@eyec0de.com
Fetching results from 15 to 20
Person [id=2259, name=JEANNIE RANDOLPH, address=672 EDISON PATH,CENTERVILLE,48580, email=wornto@eyec0de.net
Person [id=8264, name=RACHAEL CONLEY, address=1223 STEVENS CT,CARROLLTON,40084, email=smokewhite20@eyec0de.net
</pre>
</li>
</ol>
<h2>Creating a Swing Client</h2>
<p>DataValve provides an interface for data access that can be used by different clients. Lets look at using our provider with a Swing <code>JTable</code>.</p>
<ol>
<li>Start by creating a new class that will be the Swing frame that contains the table and the scroll pane.
<pre class="brush: java;">
public class CsvTableFrame extends JFrame {

	private JTable table;
	private JScrollPane pane;

	public CsvTableFrame(CommaDelimitedProvider&lt;Person&gt; provider) {
		initControls();
		initModel(provider);
	}

        //here we will create the table model and attach the provider
	private void initModel(CommaDelimitedProvider&lt;Person&gt; provider) {
	}

        //construct the gui table and scrollable panel
 	private void initControls() {
		setTitle(&quot;CSV Data&quot;);
		setSize(400, 400);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setVisible(true);

		table = new JTable();
		pane = new JScrollPane(table);
		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		getContentPane().add(pane);
	}
}
</pre>
<p>This will setup the display for showing a frame with a scrollable table in it.
</li>
<li>Now we need to implement the <code>initModel</code> method which will create a <code>ProviderTableModel</code> and attach the provider passed in. The table model class enables us to present our data to the Swing table in a way it understands. The <code>ProviderTableModel</code> implements a method which supplies column values to the model from the data supplied by the provider. The columns are defined in the latter half of the method and determines the order used to supply data to the table for each column.
<pre class="brush: java;">
        //here we will create the table model and attach the provider
	private void initModel(CommaDelimitedProvider&lt;Person&gt; provider) {
		ProviderTableModel&lt;Person&gt; model = new ProviderTableModel&lt;Person&gt;(
				provider) {

			@Override
			protected Object getColumnValue(Person person, int column) {
				switch (column) {
				case 0:
					return person.getId();
				case 1:
					return person.getName();
				case 2:
					return person.getEmail();
				case 3:
					return person.getAddressText();
				default:
					throw new RuntimeException(
							&quot;Unexpected column for person object &quot; + column);
				}
			}
		};

		//add the columns to the model
		model.addColumn(&quot;Id&quot;);
		model.addColumn(&quot;Name&quot;);
		model.addColumn(&quot;Email&quot;);
		model.addColumn(&quot;Address&quot;);

		//assign this model to the table
		table.setModel(model);
	}
</pre>
</li>
<li>The last piece we need to change is in the <code>main</code> method where we will create our provider and then pass it into the creation of our Swing frame.
<pre class="brush: java;">
public static void main(String[] args) {

	CommaDelimitedProvider&lt;Person&gt; provider;

	provider = ProviderFactory.createProvider();

	new CsvTableFrame(provider);

}
</pre>
<p>Creating the <code>CsvTableFrame</code> initializes and shows the Swing window.
</li>
<li>If we run this now, we will get a Swing Window which contains a table with our data in it.
<div class="contentBox alignCenter">
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/07/csv_swing_table.png" target="_blank"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/07/csv_swing_table-300x163.png" alt="CSV Swing Table DataValve" title="CSV Swing Table DataValve" width="300" height="163" border=0/></a>
</div>
</li>
</ol>
<p>The model controls the flow of the data and even includes built-in caching and look-ahead loading so no matter how big your CSV dataset is, there is no long delay while the data is loaded and converted to Java objects.  In this case, we pass only the provider to the model and the model is responsible for how much data is fetched in each batch. </p>
<p>If you look in the log as you scroll down the list, you will see that it is loading in the data as you scroll. If you go to the end of the list, and start slowly scrolling back up, you won&#8217;t see any more loading messages until you get to the top of the list. This is because the values are cached, but if you have a large dataset, the least recently used items (i.e. those at the top of the table) are removed from the cache and therefore need re-loading when you go back to the start of the list. </p>
<h1>Creating a JSF Client</h1>
<p>The DataValve API allows us to re-use providers with many different clients which we&#8217;ll demonstrate with JSF. </p>
<ol>
<li>Start by creating a new JSF web application, or use the <a href="http://www.andygibson.net/blog/projects/knappsack">Knappsack Archetypes</a> for Maven to get started quickly. Use the basic archetype so there is no existing application in there or alternative <code>Person</code> objects to clash with.</li>
<li>Add the <code>datavalve-dataset</code> API and the <code>datavalve-faces</code> dependencies to the project,
<pre class="brush: xml;">
		&lt;dependency&gt;
			&lt;groupId&gt;org.fluttercode.datavalve&lt;/groupId&gt;
			&lt;artifactId&gt;datavalve-dataset&lt;/artifactId&gt;
			&lt;version&gt;0.9.0.CR2&lt;/version&gt;
		&lt;/dependency&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.fluttercode.datavalve&lt;/groupId&gt;
			&lt;artifactId&gt;datavalve-faces&lt;/artifactId&gt;
			&lt;version&gt;0.9.0.CR2&lt;/version&gt;
		&lt;/dependency&gt;
</pre>
</li>
<li>For convenience, copy the <code>ProviderFactory.java</code>,<code>Person.java</code> and <code>PersonRowMapper.java</code> classes over to the new project.
</li>
<li>Create a new class called that will be our backing bean that will hold the dataset the JSF page will go against.
<pre class="brush: java;">
@Named(&quot;csvDataset&quot;)
@RequestScoped
public class CsvDatasetBean {

	CommaDelimitedDataset&lt;Person&gt; dataset =
	     new CommaDelimitedDataset&lt;Person&gt;(ProviderFactory.createProvider());

	public CsvDatasetBean() {
		//initialize the dataset settings
		dataset.setMaxRows(10);
	}

	public CommaDelimitedDataset&lt;Person&gt; getDataset() {
		return dataset;
	}
}
</pre>
</li>
<li>Now we have created the backing bean pieces, open <code>home.xhtml</code> to edit it, and replace the hello world text with the following :
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;ui:composition xmlns=&quot;http://www.w3.org/1999/xhtml&quot;
	xmlns:ui=&quot;http://java.sun.com/jsf/facelets&quot;
	xmlns:f=&quot;http://java.sun.com/jsf/core&quot;
	xmlns:h=&quot;http://java.sun.com/jsf/html&quot;
	xmlns:dv=&quot;http://java.sun.com/jsf/composite/datavalve&quot;
	template=&quot;/WEB-INF/templates/template.xhtml&quot;&gt;
	&lt;ui:define name=&quot;content&quot;&gt;
		&lt;h:dataTable value=&quot;#{csvDataset.dataset.resultList}&quot; var=&quot;v_person&quot;&gt;
			&lt;h:column&gt;
				&lt;f:facet name=&quot;header&quot;&gt;ID&lt;/f:facet&gt;
				&lt;h:outputText value=&quot;#{v_person.id}&quot; /&gt;
			&lt;/h:column&gt;

			&lt;h:column&gt;
				&lt;f:facet name=&quot;header&quot;&gt;Name&lt;/f:facet&gt;
				&lt;h:outputText value=&quot;#{v_person.name}&quot; /&gt;
			&lt;/h:column&gt;

			&lt;h:column&gt;
				&lt;f:facet name=&quot;header&quot;&gt;Email&lt;/f:facet&gt;
				&lt;h:outputText value=&quot;#{v_person.email}&quot; /&gt;
			&lt;/h:column&gt;

		&lt;/h:dataTable&gt;
		&lt;h:form&gt;
			&lt;dv:simplePaginator paginator=&quot;#{csvDataset.dataset}&quot; /&gt;
		&lt;/h:form&gt;
	&lt;/ui:define&gt;
&lt;/ui:composition&gt;
</pre>
<p>This page contains a table that takes the results from <code>#{csvDataset.dataset.resultList}</code> and displays the id, name and email fields. The last item wrapped in a form is the <code>datavalve-faces</code> default paginator which allows to you scroll across the data. This is provided as part of <code>datavalve-faces</code> and the namespace is added at the top of the page.  With JSF 2.0 including support for AJAX, you can have AJAX enabled pagination by setting the attributes on the component.</p>
<div class="contentBox alignCenter">
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/07/csv_jsf_table.png" target="_blank"><img border=0 src="http://www.andygibson.net/blog/wp-content/uploads/2010/07/csv_jsf_table-300x181.png" alt="CSV JSF Table DataValve" title="CSV JSF Table DataValve" width="300" height="181" border=0 /></a>
</div>
</li>
</ol>
<h2>Summary</h2>
<p>This tutorial has shown how to consume csv files in a way that is re-usable across different client applications using DataValve. Alternatively, if you change the implementation of <code>ProviderFactory.createProvider</code> to return a different type of provider (i.e. JDBC, ORM, Hibernate) as long is it returns the same kind of <code>Person</code> object, your code will run unchanged in the clients you create. Given the simplicity of the DataValve interfaces, it is not hard to see how easy it is to create providers for other file types whether they be text or binary based.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/tutorial/accessing-and-paginating-csv-files-with-datavalve/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Implementing User Selectable Themes In JSF</title>
		<link>http://www.andygibson.net/blog/tutorial/implementing-user-selectable-themes-in-jsf/</link>
		<comments>http://www.andygibson.net/blog/tutorial/implementing-user-selectable-themes-in-jsf/#comments</comments>
		<pubDate>Wed, 28 Jul 2010 16:44:36 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[Journeyman]]></category>
		<category><![CDATA[JSF]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1116</guid>
		<description><![CDATA[

Prerequisites
Install Maven
Install the Knappsack Archetypes


Many web applications offer users the option to change the appearance of user interface. One of the easiest ways to implement this is by offering different page color schemes by selecting different css style sheets. This article describes how to implement themes in JSF using CDI backing beans that the user [...]]]></description>
			<content:encoded><![CDATA[<div class="prereq floatRight" >
<ul>
<lh>Prerequisites</lh></p>
<li>Install Maven</li>
<li><a href="http://www.andygibson.net/tutorial/installing-the-knappsack-archetypes/">Install the Knappsack Archetypes</a></li>
</ul>
</div>
<p>Many web applications offer users the option to change the appearance of user interface. One of the easiest ways to implement this is by offering different page color schemes by selecting different css style sheets. This article describes how to implement themes in JSF using CDI backing beans that the user can select as their default theme.<br />
<span id="more-1116"></span><br />
<a href='http://www.andygibson.net/blog/wp-content/uploads/2010/07/jsfthemes.zip'>Download project source</a><br/><br />
Each style sheet implements a different color scheme and when they user picks a theme, you simply have to provide the style sheet assigned to that theme. The application will be based on an existing archetype, so we&#8217;ll start by creating a new Maven application using the <code>jee6-sandbox-demo-archetype</code>. </p>
<p>As it is, the application has a stylesheet called <code>screen.css</code> which includes color information for the pages. We want to add another style sheet that overrides those color choices for the elements that we want to change per theme. </p>
<p>Of course, we could change much more css than the colors in the theme style sheet, we could change the layout and sizing information also, but the tradeoff is that the more content we put into the theme stylesheet, the more content we have to duplicate in each theme, and the more we have to change each time there is a minor change. We could resolve this problem by giving the user two different theming option, the first would select the layout stylesheet and the other would select the color stylesheet.</p>
<ol>
<li>In the package explorer locate the <code>bean</code> package and right click on the package folder.</li>
<li>Select <i>New->Class</i> and in the class dialog, enter <code>StyleBean</code> as the name of the class<br />
<img src="img"/><br />
This bean will hold the value of the current theme name and return the style sheet name to our view. It will also hold the list of available style sheets.
</li>
<li>We&#8217;ll start by annotating the bean with the <code>@Named</code> annotation so we can reference it from our JSF view pages and make the bean <code>@SessionScoped</code> so it will remember the settings between each request. </li>
<li>Since our bean is session scoped, it needs to be passivation capable which means adding the <code>Serializable</code> interface to the implements clause.</li>
<li>We add fields for the currently selected theme, and also a theme map which will contain the name of the themes and the stylesheet associated with it. Getters and setters for the <code>theme</code> have been omitted.</li>
<pre class="brush: java;">
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Named;

@Named(&quot;styleBean&quot;)
@SessionScoped
public class StyleBean implements Serializable {

	private String theme;

	private Map&lt;String, String&gt; themeMap;

	public StyleBean() {
		themeMap = new LinkedHashMap&lt;String, String&gt;();
		// read this list from the db or something
		themeMap.put(&quot;Default&quot;, &quot;default.css&quot;);
		themeMap.put(&quot;Blue&quot;, &quot;blue.css&quot;);
		themeMap.put(&quot;Green&quot;, &quot;green.css&quot;);
	}

}
</pre>
<li>Because JSF cannot iterate over a <code>Map</code> or <code>Set</code> we need to convert the list of theme names into a <code>List</code>. We do this with another method that we annotate with the <code>@Produces</code> method to indicate that this produces values. We give it the name <code>themes</code> and make it application scoped so this will be produced only once per application.
<pre class="brush: java;">

	@Produces
	@Named(&quot;themes&quot;)
	@ApplicationScoped
	public List&lt;String&gt; getThemes() {
		return new ArrayList&lt;String&gt;(themeMap.keySet());
	}
</pre>
</li>
<li>We have one more method to implement and that is the method that returns the name of the CSS stylesheet for the selected theme. We do this by using our theme <code>Map</code> as a lookup to get the filename</li>
<pre class="brush: java;">

	public String getThemeCss() {
		return themeMap.get(getTheme());
	}
</pre>
<p>If you get an error at this point you forgot to put in the getter/setters for the theme field. </p>
</ol>
<p>Now we have put all our code together in one bean, given that bean a name so it can be referenced from JSF, and implemented the list of themes and converting themes to a CSS file name. It&#8217;s time to implement our options page that lists the themes available and lets the user select one. </p>
<ol>
<li>Create a new JSF page called <code>options.xhtml</code> and paste in the following code :
<pre class="brush: xml; highlight: [12,13,14];">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;ui:composition xmlns=&quot;http://www.w3.org/1999/xhtml&quot;
	xmlns:ui=&quot;http://java.sun.com/jsf/facelets&quot;
	xmlns:f=&quot;http://java.sun.com/jsf/core&quot;
	xmlns:h=&quot;http://java.sun.com/jsf/html&quot;
	xmlns:fc=&quot;http://java.sun.com/jsf/composite/fluttercode/component&quot;
	template=&quot;/WEB-INF/templates/template.xhtml&quot;&gt;
	&lt;ui:define name=&quot;content&quot;&gt;
		&lt;h:form&gt;
			&lt;fc:panel caption=&quot;Visual Options&quot;&gt;
				&lt;fc:property caption=&quot;Theme&quot;&gt;
					&lt;h:selectOneListbox value=&quot;#{styleBean.theme}&quot; style=&quot;width : 180px;height : 180px&quot;&gt;
						&lt;f:selectItems value=&quot;#{styleBean.themes}&quot; /&gt;
					&lt;/h:selectOneListbox&gt;
				&lt;/fc:property&gt;
				&lt;h:commandButton value=&quot;Update&quot;/&gt;
			&lt;/fc:panel&gt;

		&lt;/h:form&gt;

	&lt;/ui:define&gt;
&lt;/ui:composition&gt;
</pre>
<p>Most of this code is boilerplate so I&#8217;ve highlighted the relevant parts. The list box that is wrapped by the property component, takes the list of themes from our <code>themes</code> producer and is bound to the <code>theme</code> property of our <code>styleBean</code>. When the user selects an item and clicks the Update button the <code>theme</code> property is set to the name of the selected theme.Since this is stateful, the new value holds across page requests so next time the page is rendered we can look at the <code>themeCss</code> property to get the file name of the css file for the selected theme.</p>
<li>To render the css style sheet we need to add it to the style sheets in the header. Open up the <code>template.xhtml</code> file and locate the line with <code>&lt;h:outputStylesheet name="css/screen.css" /&gt;</code>. Underneath it, add a new line to include our user selected style sheet.
<pre class="brush: xml;">
&lt;h:outputStylesheet name=&quot;css/#{styleBean.themeCss}&quot; /&gt;
</pre>
</li>
<li>Now the only thing left is to create the additional stylesheets for our themes. In the <code>src/main/webapp/resources/css/</code> folder create a new stylesheet called <code>default.css</code> but leave it blank.</li>
<li>Create a new stylesheet called <code>blue.css</code> with the following content :
<pre class="brush: css;">

body {
	background-color: #E0E0FF;
	color: #102040;
}

#header {
	background: #204080;
	color: #f0f0fF;
}

.panel {
	border: 1px solid #D0D0F0;
	background: #f0f0ff;
}

.panel h1 {
	background: #e0e0f0;
	border-bottom: solid 1px #D0D0F0;
	color: #102040;
}

.odd {
	background: #f0f0fF;
}

.even {
	background: #f7f7ff;
}

.dataTable th {
	background: #204080;
	color: #f0f0ff;
}
</pre>
</li>
<li>Add one more stylesheet called <code>green.css</code> with the following content :
<pre class="brush: css;">
body {
	background-color: #E0FFE0;
	color: #104020;
}

#header {
	background: #208040;
	color: #f0fFF0;
}

.panel {
	border: 1px solid #D0F0D0;
	background: #f0fff0;
}

.panel h1 {
	background: #e0f0e0;
	border-bottom: solid 1px #D0F0D0;
	color: #104020;
}

.odd {
	background: #f0fFf0;
}

.even {
	background: #f7fFf7;
}

.dataTable th {
	background: #208040;
	color: #f0fff0;
}
</pre>
</li>
<p>If you deploy the application now and go to the <a href="http://localhost:8080/jsfthemes/options.jsf">http://localhost:8080/jsfthemes/options.jsf</a> you can pick a different theme,click update and the application will start rendering pages with the new themes.</p>
<h1>Extending the Implementation</h1>
<p>There are a number of ways we can improve this implementation, especially since we are keeping the list of styles and the selection information in a backing bean in the session. Chances are that the session already has some kind of User entity, and it would be a good idea to store the selected theme, or better yet, the name of the css file as part of the user profile. The list of themes is only needed when the user is on the options page and is only used to provide the list of themes and to convert from the theme name to the css file. It would be easy to re-implement these as request scoped elements once the state is moved to the user entity.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/tutorial/implementing-user-selectable-themes-in-jsf/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>FlutterCode.com released</title>
		<link>http://www.andygibson.net/blog/news/fluttercode-com-released/</link>
		<comments>http://www.andygibson.net/blog/news/fluttercode-com-released/#comments</comments>
		<pubDate>Tue, 29 Jun 2010 02:48:18 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[Blog]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Geek]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Personal]]></category>
		<category><![CDATA[Podcast]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=919</guid>
		<description><![CDATA[I&#8217;ve been fairly quiet over the last couple of months as I&#8217;ve been working on a few items, working on a new site and working on getting two new Open Source projects final and out the door. 
I&#8217;ve renamed Spigot to DataValve, and moved it to the new site FlutterCode.com which will also host my [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been fairly quiet over the last couple of months as I&#8217;ve been working on a few items, working on a <a href="http://www.fluttercode.com">new site</a> and working on getting two new Open Source projects final and out the door. </p>
<p>I&#8217;ve renamed Spigot to <a href="http://www.fluttercode.com/projects/datavalve">DataValve</a>, and moved it to the new site FlutterCode.com which will also host my other project called <a href="http://www.fluttercode.com/projects/knappsack">Knappsack</a> which is a set of Maven archetypes for Java EE 6.</p>
<p>The new site will be home to most of my tutorials, articles and other writings, as well as possibly some screencasts and even podcasts. It will in essence be a pure java development site. This blog will go a bit quieter and contain less development stuff, although most opinion will get put out here instead of over there. I&#8217;ll also be copying some of my tutorials over there from this blog.</p>
<p>I&#8217;m aiming to create a fairly cohesive tutorial site, aided in part by the Maven Archetypes which will give me a firm base onto which I can build tutorials without having to start from scratch, but one archetype is a sandbox Java EE 6 app with project configuration, a demo model and some test data. The sandbox app will let developers create a new skeleton java EE 6 application they can play with. Building on that, there is a sandbox-demo application which as an archetype that creates a full working demo CRUD application using Java EE 6 so developers can see how all the different pieces of Java EE 6 go together. It includes features such as conversations, JPA CRUD, page parameters, CDI injection and events.</p>
<p>Again, I have to say it, but  <a href="http://www.andygibson.net/blog/index.php/2009/07/12/open-source-is-hard/">Open Source is Hard</a>. In the past couple of months, I have been working on a whole new site, getting 2 projects ready to roll with documentation and site content to boot as well as working a job, and having some kind of life.</p>
<p>Now it&#8217;s out, I can start to focus a little more on getting some more Java EE 6 tutorials and articles out.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/news/fluttercode-com-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Guide to Spigot For Seam Developers</title>
		<link>http://www.andygibson.net/blog/article/spigot-for-seam-developers/</link>
		<comments>http://www.andygibson.net/blog/article/spigot-for-seam-developers/#comments</comments>
		<pubDate>Tue, 06 Apr 2010 17:00:57 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Project Kenai]]></category>
		<category><![CDATA[Seam]]></category>
		<category><![CDATA[Spigot]]></category>
		<category><![CDATA[Weld]]></category>
		<category><![CDATA[Wicket]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=874</guid>
		<description><![CDATA[Note : Spigot has been renamed to DataValve.
(Edit : I renamed this post so it doesn&#8217;t seem like Spigot is just for Seam, Spigot can be used with different frameworks or without any at all. However, I wrote this post since Spigot is so familiar to the Seam EntityQuery that it should be easy for [...]]]></description>
			<content:encoded><![CDATA[<p><b>Note</b> : Spigot has been renamed to <a href="http://www.fluttercode.com/projects/datavalve/">DataValve</a>.</p>
<p>(<small><b>Edit </b>: I renamed this post so it doesn&#8217;t seem like Spigot is just for Seam, Spigot can be used with different frameworks or without any at all. However, I wrote this post since Spigot is so familiar to the Seam EntityQuery that it should be easy for Seam users to get the idea</small>)</p>
<p>Seam developers should become familiar with <a href="http://kenai.com/projects/spigot/">Spigot</a> concepts fairly quickly since they are very similar to those found in the Seam <code>EntityQuery</code> which was one of the main inspirations for the framework. If you imagine taking the entity query class and splitting it in two, one part to keep hold of state and the other to actually fetch the data. The stateful part is the <code>Paginator</code> that keeps track of what the current ordering of the data is, what is the current page and how big the pages are. The stateless part takes the Ejbql and the pagination information and returns a subset of the data. Now imaging that the data provider has the JPA pieces taken out and replaced with an abstract <code>fetchResults</code> method. This method is implemented in subclasses for specific data providers for text files, sql queries, jpa queries, native jpa queries, xml files, comma delimited or just an in memory dataset.<br />
<span id="more-874"></span><br />
I also abstracted the concepts of parameterization and parameter resolution so you can have parameters on data providers that are no t query based and your parameters can be resolved using different mechanisms such as EL, reflection, a map, or using custom parameter resolution.<br />
So really, for Seam developers, its like a Seam <code>EntityQuery</code> that doesn&#8217;t just use JPA, but uses any kind of data source you want but still returns just a list of objects.</p>
<p>Spigot works nicely with CDI and there is even a demo of it in the distribution that uses JSF and was generated using the Weld maven archetypes. Also, there is a Seam Jpa Dataset Adapter that you can use as a direct replacement for the <code>EntityQuery</code> which will adapt the entity query calls to the underlying data provider calls so you can have a seam-less transition if you want to switch over. This is still a little in-progress, but works. The one area that isn&#8217;t implemented is the sorting, which may not be possible, but I still need to add in the methods to the adapter even if they don&#8217;t do anything. The other issue is of course the configuration of the query from components.xml using the Seam Framework tags. However, you can define the query using regular component xml tags to define the Ejbql, restrictions and page sizes.</p>
<p>Two things to note if you start using Spigot in place of the entity query. All rows are returned by default, and you need to specify both a select statement and a count statement. I separated those two out so you can put join fetch phrases in the select statement without it breaking the count statement. There is an <code>init</code> method that you can use to set both of these statements for a class type.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/spigot-for-seam-developers/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Spigot 0.9.CR1 released</title>
		<link>http://www.andygibson.net/blog/news/spigot-0-9-cr1-released/</link>
		<comments>http://www.andygibson.net/blog/news/spigot-0-9-cr1-released/#comments</comments>
		<pubDate>Tue, 06 Apr 2010 13:07:55 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Personal]]></category>
		<category><![CDATA[Seam]]></category>
		<category><![CDATA[Spigot]]></category>
		<category><![CDATA[Weld]]></category>
		<category><![CDATA[Wicket]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=861</guid>
		<description><![CDATA[Note : Spigot has been renamed to DataValve and is hosted over on FlutterCode.com.
It&#8217;s been a while since I&#8217;ve posted anything new as I&#8217;ve been busy with a new Open Source software project called Spigot. It&#8217;s a java library that sits between your application code and your data sources (Hibernate, JPA, JDBC or any arbitrary [...]]]></description>
			<content:encoded><![CDATA[<p><b>Note</b> : Spigot has been renamed to <a href="http://www.fluttercode.com/projects/datavalve/">DataValve</a> and is hosted over on <a href="http://www.fluttercode.com">FlutterCode.com</a>.</p>
<p>It&#8217;s been a while since I&#8217;ve posted anything new as I&#8217;ve been busy with a new Open Source software project called Spigot. It&#8217;s a java library that sits between your application code and your data sources (Hibernate, JPA, JDBC or any arbitrary source of data) and helps with things like pagination and sorting using a common interface so you can switch out data providers and use alternatives. </p>
<p>For query language data providers, Spigot also facilitates excluding restrictions from WHERE clauses when parameters are resolved to null. Parameters are handled using parameter resolvers so there is more than one way to parameterize the query including EL expressions, reflection or a value map on the data provider.</p>
<p>Spigot also provides a few other add-ins like converting any dataset into an in-memory dataset that can itself be paginated and sorted and shared across an application (such as commonly used data in a web application). The <code>IndexedDataProviderCache</code> can give you random access into a dataset with caching and look ahead loading. This lets you hook a dataset with thousands of rows up to a Swing JTable with an instant response and a very small memory footprint since it doesn&#8217;t need to load all the objects at once as the provider will load the records as needed and cache the results. This is demonstrated in the Swing Demo in the download. There are also demos for Wicket and CDI with JSF.</p>
<p>You can ready about why I created Spigot in the <a href="http://spigot.kenai.com/docs/html/pr01.html">documentation</a></p>
<p>Spigot is currently hosted on <a href="http://www.projectkenai.com/projects/spigot/">Project Kenai</a>, where you can download the release, view documentation online or read about <a href="http://kenai.com/projects/spigot/pages/10WaysSpigotHelpsDevelopers">10 ways Spigot helps developers</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/news/spigot-0-9-cr1-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Weld 1.0.1-CR2 is available</title>
		<link>http://www.andygibson.net/blog/news/weld-1-0-1-cr2-is-available/</link>
		<comments>http://www.andygibson.net/blog/news/weld-1-0-1-cr2-is-available/#comments</comments>
		<pubDate>Sun, 14 Feb 2010 17:28:54 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[JSF]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=830</guid>
		<description><![CDATA[Dan Allen posted that the latest CR version of Weld is available. This should contain a number of bug fixes from the initial release of Weld, including the two problems I had with the request scope being available in EJB timeouts and problems with the ability to proxy stateless beans. This last bug was for [...]]]></description>
			<content:encoded><![CDATA[<p>Dan Allen <a href="http://in.relation.to/14291.lace">posted</a> that the latest CR version of Weld is available. This should contain a number of bug fixes from the initial release of Weld, including the two problems I had with the request scope being available in EJB timeouts and problems with the ability to proxy stateless beans. This last bug was for me rather crucial since there was no easy way to implement DAO (just data management) type components with transactional annotations that could be injected into business logic beans. Without that, you end up having to write your own transaction handling code. </p>
<p>Also in the comments of the announcement, Max Anderson notes that the nightly builds of JBoss Tools 3.1 now supports CDI auto completion and JSF 2.0. I had a very quick look at it yesterday and it looks promising. I also tried it out with the latest JBoss 6 snapshot and am very pleased to say that the redeployment times on JBoss 6 are much faster and more in line with the performance on  Glassfish which is something I have raved about. </p>
<p>I&#8217;ll be looking at it some more and probably write up a couple of tutorial posts. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/news/weld-1-0-1-cr2-is-available/feed/</wfw:commentRss>
		<slash:comments>0</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>Conversational Pitfalls</title>
		<link>http://www.andygibson.net/blog/article/conversational-pitfalls/</link>
		<comments>http://www.andygibson.net/blog/article/conversational-pitfalls/#comments</comments>
		<pubDate>Wed, 18 Nov 2009 01:44:52 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Seam]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=524</guid>
		<description><![CDATA[Seam conversations have certain rules that you need to be aware of when using them. This article came about because for the last couple of years, the same questions have been asked on the Seam forums regarding conversations. It is also a couple of issues that cropped up while I was working on the Seam [...]]]></description>
			<content:encoded><![CDATA[<p>Seam conversations have certain rules that you need to be aware of when using them. This article came about because for the last couple of years, the same questions have been asked on the Seam forums regarding conversations. It is also a couple of issues that cropped up while I was working on the Seam vs. Spring Web Flow articles. Some of the problems are uncannily similar with similar solutions, so parts of this series may be of interest to non-Seam users. Additionally, it seems like a lot of this stuff will also apply to the conversational pieces of JSR 299 &#8211; Contexts and Dependency Injection which will be a part of JEE 6.<br />
<span id="more-524"></span></p>
<h1>Conversational Fundamentals</h1>
<p>Let&#8217;s start with a fairly descriptive and steady paced description of what conversations are and what they are not. Some of these behaviors are probably more figurative that literal. This mainly applies to Seam, but is also similar to CDI.</p>
<p>Conversations in Seam are like buckets that hold conversational data. A user session has a list of conversation contexts each identified by a conversation Id. A conversation is either long running or temporary and even when you are not in a long running conversation, you are using a temporary conversational context or bucket. The only difference between a long running conversation and a temporary conversation is the boolean <code>longRunning</code> flag on the conversation instance. When you start a conversation, all that happens is the <code>longRunning</code> flag on the conversation is set to true. When you end the conversation, the <code>longRunning</code> flag is cleared. There is no destruction of conversational objects and no clearing out of the conversation. Abandoned long running conversations sit in the conversation list until they time out. Note that in JCDI (JSR 299), the long running flag has been renamed to a <code>isTransient</code> flag on the conversation. </p>
<p>Components that are scoped to the conversation are still held in the conversation context regardless of whether it is long running or temporary. The only difference with a long running conversation is that the id for the conversation is propagated from one page to the next. When the id is propagated, that same conversation &#8216;bucket&#8217; is used by the next page and the objects that were in the previous page are accessible in the new page. In each request, Seam determines if the conversation is long running, and if so, it passes the conversation id to the next page as a parameter. Obviously, this propagation only takes place with faces requests, or GET requests that have special handling like manual conversation propagation or you are using the Seam JSF controls that provide GET requests with automatic conversation propagation. </p>
<p>When rendering a new page, at some point Seam will need to access the conversational context. It does this by looking to see if the request contained a conversation id and if so, looking up the existing conversation context instance for that id. Otherwise, it obtains a new conversation instance with a new conversation Id. When there is no long running conversation, no id is propagated so each page obtains a new conversation instance and Id. When we start a long running conversation Seam will automatically propagate the conversation id from one page to the next for us which is how we write applications with multiple pages using the same conversation. </p>
<p>When you end a conversation, the <code>longRunning</code> flag is set to false and Seam no longer propagates the id from one page to the next. However, when you end a conversation on one page, Seam will still propagate the conversation to the next page one last time. This allows us to carry things like faces messages and any other data over the conversation boundary. This next page gets to use the same conversation instance that just finished outside of the conversation boundary. It has a number of benefits as well as some important consequences that can cause many problems that are tricky to track down.</p>
<p>If you end your conversation and set the <code>before-redirect</code> attribute to true the conversation is ended before the redirect so the conversation id is not propagated and the new page starts with a fresh conversation context. The problem with this is that since there is no propagation of the conversation, faces messages (and any other information you wanted to carry to the new page) is not propagated either. This is to be expected since you explicitly specified that you wanted to end the conversation before the new page.</p>
<p>There are also times when Seam will propagate the conversation from one page to the next when it is not long running. If a redirect is taking place, then Seam promotes the conversation to long running temporarily so the conversation id parameter is passed to the redirect. The conversation is then demoted again to a temporary conversation. This allows items such as faces messages to propagate so you can show messages even after a redirect.</p>
<p>One useful way of seeing which conversation you are using is to add <code>Conversation = #{conversation.id}</code> to your template so you can see what conversation id the page is using. This way you can see whether or not the conversation has propagated and whether you are using the same value from the previous page. If the conversation id on two pages is the same, they are using the same conversation instance and sharing data.</p>
<p>Hopefully, this section has provided enough of an overview into Seam conversations, cleared some of the misconceptions up and will make understanding some of the conversational pitfalls easier.</p>
<h1>Dirty Data</h1>
<p>When you end a conversation, the conversation instance contains multiple pieces of data. Let&#8217;s take the scenario of editing a widget, and clicking save or cancel and being taken back to the widget view page. Our Seam page uses a factory method to generate the <code>#{widget}</code> instance from our <code>WidgetHome</code> bean. We may edit the instance, and post back the changes, and then decide to cancel our changes. At this point, our widget in the conversation is dirty, it has changes made to it that we have cancelled. If we do nothing and just go back to the view page, the conversation will be re-used since we propagate that ended conversation id over one last time. The <code>#{widget}</code> references in the view page will refer to our existing dirty instance in the re-used conversation. Since the variable exists in the conversation already, Seam won&#8217;t call the factory method to get a fresh instance.  As a result our view page shows the dirty instance with all our modifications.</p>
<p>This problem can be solved in a couple of different ways, each with its own problems. The simplest is to use <code>before-redirect=true</code> when ending the conversation. This way our view page won&#8217;t use the dirty data from the ended conversation and it starts with a fresh conversation. This may be a problem though if you are passing the widgetId parameter from the previous page. Pages.xml lets you easily add parameters to redirects, but pageflows don&#8217;t. It also means that you won&#8217;t be able to pass any other data over such as a message to say you have cancelled changes. Another similar, but more forceful, way of doing this is just to have a non-faces &#8216;cancel&#8217; link on your edit page that takes you straight to the edit page with a GET request and passes in the widget Id. In this scenario, the conversation is abandoned since we used a link and it will not propagate the conversation or the associated dirty data over with it, nor can you pass any cancellation messages over.</p>
<p>The other method is to let the view page re-use the conversation, but when the user cancels the changes, actually refresh the entity that has been changed. You create a cancel method on the entity home bean which is called when the user cancels their changes and it will refresh the entity so it is no longer dirty. This has the benefit of causing minimal disruption, but if you have a long chain of objects that ended up dirty, making sure you refresh them all can be tricky. </p>
<h1>Stale Data</h1>
<p>The stale data problem is similar to the dirty data problem except the problem occurs within the same conversation and without ending it. If we have some data in a conversation that depends on other values in the conversation, when those values change, we have to make sure we update our data, otherwise it will become stale. For example a paginated list of sales orders from on an EntityQuery means that we need to get a new set of results when we click next or previous. However, if the results of the query are outjected from the query bean and referenced as <code>#{orderList}</code> in the JSF page, then we will see the stale data problem. The first time we enter the page, the variable <code>#{orderList}</code> doesn&#8217;t exist, so Seam calls the factory for <code>#{orderList}</code> which returns the list of the first 10 results.  Our datatable shows the list of results using the variable <code>orderlist</code>.</p>
<pre class="brush: xml;">
&lt;h:dataTable value=&quot;#{orderList}&quot;&gt;
  &lt;!-- Columns Here --&gt;
&lt;/h:dataTable&gt;
</pre>
<p>The user clicks next in the paginator which does a postback, increases the <code>firstResult</code> value and causes a refresh on the result list referenced by the entity query to show the next 10 results. The page is rendered but the displayed results are exactly the same. We are still looking at the first 10 rows. Why? Because the <code>orderList</code> context variable is used by the view to obtain the list of orders. When the page is rendered the second time, JSF looks for the value of <code>#{orderList}</code> and finds it already exists in the conversational context even though it contains the first 10 results, and not the second 10. Seam has no reason to call the factory method to obtain the latest values. In essence, we have two sets of results, the original set which is referenced by the <code>orderList</code> seam variable, and the current set which is the correct list of results and is held by the query bean. </p>
<p>We have two ways of fixing this problem. The first is to change the value our data table is referencing so it is always referencing the result set on the query bean directly.</p>
<pre class="brush: xml;">
&lt;h:dataTable value=&quot;#{orderQuery.resultList}&quot;&gt;
  &lt;!-- Columns Here --&gt;
&lt;/h:dataTable&gt;
</pre>
<p>With this code, there is no El expression used that can become stale. When the page is re-rendered the table will get the results from the order query directly each time ensuring that the most up to date values are used. This is the easiest solution but it cannot be used if you are using the <code>DataModel</code> annotation since Seam requires you to use the outjected data model variable. In such cases refer to the second solution which is to invalidate the <code>orderList</code> variable when we refresh the search results. This is fairly easy, but requires us to override the <code>refresh</code> method in the entity query. When we refresh the list of orders, we simply remove the <code>#{orderList}</code> context variable. i.e.</p>
<pre class="brush: java;">
@Override
public void refresh()
{
    super.refresh();
    Contexts.removeFromAllContexts(&quot;orderList&quot;);
}
</pre>
<p>This means that when the user causes a refresh of the query data, the variables referencing that data will be ejected from all contexts and the next time that value is requested in a JSF page, the appropriate Seam factory will be called to get the most up to date result set.</p>
<h1>Starting a conversation</h1>
<p>Even starting a conversation can be a problem. In most cases, we utilize the <code>join="true"</code> attribute to gloss over the fact that we are going into a page that requires a conversation with or without a conversation already started. When we hit our target page, we know that we will be in a conversation, either a newly started one, or an existing conversation. We may not care which except that not considering our conversation start and end points has side effects. Using the join attribute is not a substitue for thinking about conversation demarcation.</p>
<p>First is the issue of old data where a new page may re-use data from the last page because they share the conversation. For example, we are viewing a widget and the widget instance is loaded into the temporary conversation. 10 minutes later, we click edit which takes us to the widget edit page and starts a long running conversation. The edit page needs an instance of a widget which it already has from the view page, but this instance of a widget is 10 minutes old and has been edited by another user since you loaded the view page and therefore, you need to do a refresh. This problem arose without us even starting a long running conversation in the view page. The answer here is to ensure that you are always starting with a fresh conversation instance when you go in to the edit page. The easiest way to do that is to use <code>propagation="none"</code> on the link to edit the widget, or just use a plain old GET link.</p>
<p>If a page is meant to start a conversation and also start a pageflow then you cannot enter that page with an existing conversation. If you do, the page will join the existing conversation and the pageflow will not start. Pageflows can only be started with a fresh conversation. Note that initially a page may be simple enough that you don&#8217;t need a pageflow and you could ignore conversation demarcation, but if you later start a pageflow on that page, you could end up with all sorts of headaches as invoking that page from different places may or may not start the pageflow depending on whether the page you were on previously had a long running conversation.</p>
<h1>Menus</h1>
<p>Always consider your menus and their links and what pages they will be used in. They could be called from pages where there may or may not be a long running conversation. Consider whether that conversation is propagated or not. Typically (and luckily) most links in menus are to top level items and thus conversation propagation is never really required which means you can just never propagate it. Propagation is mostly task centric and therefore is more likely to appear in the main page itself rather than a general application wide menu.</p>
<p>One other problem I found was with rich menu items which only allow an action on the menu item. Typically to end or demarcate a conversation, you would need an <code>s:link</code> or <code>s:button</code> since only these Seam specific controls were are aware of the concept of conversation propagation. Since our menu is shared across all pages if we were in a pageflow, we could end up with Illegal Navigation issues since we don&#8217;t account for global menu navigation in our pageflows. Alternatively, we might be in a conversation and calling a page that starts a new conversation with a pageflow so we need to end the conversation before we get there so we can start the new conversation and also the new pageflow. In a nutshell, we need to end any current conversation then re-direct to a new page where we will start a new conversation. We also need to be able to do this from a JSF <code>action</code> since some menu components require actions instead of allowing you to add links.</p>
<p>One solution to this is to use a navigator component that will perform these tasks for us and we just pass in the view-id that we want to go to.</p>
<pre class="brush: java;">
@Name(&quot;navigator&quot;)
@Scope(ScopeType.STATELESS)
public class Navigator {

	public void gotoView(String view) {

		if (Conversation.instance().isLongRunning()) {
			Conversation.instance().end(true);
		}

		Redirect.instance().setViewId(view);
		Redirect.instance().execute();
	}

}
</pre>
<p>With this, we can define our action methods as <code>#{navigator.gotoView("/startBookingProcess")}</code> and when that menu item is selected, it will end the conversation and perform the redirect so on our new page we can start a new conversion and pageflow.</p>
<h1>Conversational Best Practices</h1>
<p>These are best practices that I&#8217;ve found working with Seam and conversations in general. Obviously, it&#8217;s a personal thing, and some people may disagree with me on them, but these rules have served me and my team well.</p>
<p>Always determine where a page fits in terms of conversations and always treat that page the same way. For example, edit and view pages I tend to isolate from other conversations. I tend to only use the temporary conversation for the view page so if you click refresh, it reloads the data which is really what you want, a refreshed view of what you are looking it. Any links to a view (or edit) page do not propagate the conversation at all. </p>
<p>I always start conversations in <code>pages.xml</code> since this provides a single common place to do it. I&#8217;ve never really used the annotations since it requires knowledge of the target page to know which method you need to call. To edit a widget, with pages.xml you can just go to <code>/widgetEdit.seam?widgetId=234</code> as opposed to calling a specific method annotated with <code>@Begin</code>.</p>
<p>Hope this has helped guide you through some of the complexities of conversations in Seam. Once you understand the basic principles, it makes it much easier to figure out why something isn&#8217;t working quite right, and some of these bugs relating to stale and dirty data can be subtle and sneaky.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/conversational-pitfalls/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
