<?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; Tutorials</title>
	<atom:link href="http://www.andygibson.net/blog/category/tutorial/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.andygibson.net/blog</link>
	<description>Open Source Projects &#38; Technical Writings</description>
	<lastBuildDate>Tue, 07 Feb 2012 14:19:07 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language></language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Simple RESTful services in Glassfish Pt 2</title>
		<link>http://www.andygibson.net/blog/tutorial/simple-restful-services-in-glassfish-pt-2/</link>
		<comments>http://www.andygibson.net/blog/tutorial/simple-restful-services-in-glassfish-pt-2/#comments</comments>
		<pubDate>Mon, 21 Mar 2011 12:39:13 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Glassfish]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[Journeyman]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[Web Services]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1765</guid>
		<description><![CDATA[In part 2 of this article, we are going to create a data driven web service that will return JSON and XML to the client, and then use jQuery to add a new item to the database and display it in our page. In part 1, we looked at creating simple web services and now [...]]]></description>
			<content:encoded><![CDATA[<p>In part 2 of this article, we are going to create a data driven web service that will return JSON and XML to the client, and then use jQuery to add a new item to the database and display it in our page.<br />
<span id="more-1765"></span><br />
In part 1, we looked at creating simple web services and now we&#8217;re going to look at making something more practical and interesting. We&#8217;ll start from where we left off with the source code as it was at the end of the part 1 which you can download from here (<a href="http://www.andygibson.net/blog/wp-content/uploads/2011/02/restwebdemo_pt1.zip">restwebdemo_pt1</a>) if you want to follow along. If not, the final source can be downloaded from here (<a href='http://www.andygibson.net/blog/wp-content/uploads/2011/03/restwebdemo_pt2.zip'>restwebdemo_pt2</a>).</p>
<ol>
<li>First off, we&#8217;re going to change the entity manager that is available for injection to be request scoped. To do this, open up <code>DataRepositoryProducer.java</code> and change the <code>@ConversationScoped</code> annotation on the <code>getEntityManager()</code> method to be <code>@RequestScoped</code>.  The reason for this is documented here in <a href="http://www.andygibson.net/blog/article/a-little-less-conversation/">A Little Less Conversation</a>.</li>
<li>Next we are going to create a simple dao for Course objects, and the only reason to do this is to demonstrate the integration of CDI and the ability to layer your code. Create a new class called <code>CourseDao</code> with the following code.
<pre class="brush: java;">
package org.fluttercode.restwebdemo.bean;

@Stateless
@LocalBean
public class CourseDao {

	@Inject @DataRepository
	private EntityManager entityManager;

	public void save(Course course) {
		entityManager.persist(course);
	}

	public Course update(Course course) {
		return entityManager.merge(course);
	}

	public Course find(Long id) {
		return entityManager.find(Course.class, id);
	}
}
</pre>
<p>This just injects an entityManager and uses it to locate, save and update Course objects.
</li>
<li>Now create a new <code>CourseService</code> bean that will handle the web services. To start with we want to make it a stateless EJB and inject the course Dao. We are going start by re-implementing the method to return the course name for the given id.
<pre class="brush: java;">
	@Path(&quot;courseName/{id}&quot;)
	@GET
	public String getCourseName(@PathParam(&quot;id&quot;) Long id) {
		Course course = courseDao.find(id);
		if (course == null) {
			return &quot;Course not found&quot;;
		} else {
			return course.getTitle();
		}
	}
</pre>
</ol>
<p>To see this method in action, deploy the application and go to <a href="http://localhost:8080/restwebdemo/rest/course/courseName/126">http://localhost:8080/restwebdemo/rest/course/courseName/126</a>. Now we know everything is working and hooked up together, we can look at adding some new functionality. </p>
<p>Let&#8217;s start by returning a course with a given id from the service. This is fairly simple given what we already know. The only thing to determine now is what format to return the object as and to convert it to that type. Luckily, Java EE already provides JAXB which can take an object graph and convert it to XML for us as long as we annotate the classes with the annotations to let the JAXB implementation know how to convert it. The same annotations can be used by the body writer that handles JSON.</p>
<p>First we&#8217;ll annotate the <code>Course</code> class and make a couple of changes that we need to. Next we&#8217;ll create methods to return a <code>Cource</code> object from the service in XML or JSON format.</p>
<ol>
<li>Open the <code>Course</code> class and add the following annotations to the class. </p>
<pre class="brush: java;">
@Entity
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Course extends BaseEntity {
   ...
   ...
}
</pre>
<p>This tells the JAXB processor that this class can be serialized and to access the values using fields in the class. This also means that any other annotations we want to add to control the serialization needs to be applied to the fields.
</li>
<p>This is a simple example, so we don&#8217;t want to serialize the <code>teacher</code> or <code>enrolled</code> properties which we can do by marking them with the <code>@XmlTransient</code> attributes. Also, remove the <code>@NotNull</code> annotation from the <code>teacher</code> attribute as we will need it blank later. The following code shows the fields with both the JAXB and JPA annotations. JAXB (like JPA) uses default conventions for fields that don&#8217;t have annotations : </p>
<pre class="brush: java;">
	@Column(length = 32, nullable = false)
	@Size(max = 32)
	@NotEmpty(message = &quot;title is required&quot;)
	private String title;

	@Column(length = 8, nullable = false)
	@Size(max = 8  )
	@NotEmpty(message = &quot;code is required&quot;)
	private String code;

	@ManyToOne(fetch = FetchType.LAZY)
	@XmlTransient
	private Teacher teacher;

	@ManyToMany(mappedBy = &quot;enrolled&quot;)
	@XmlTransient
	private List&lt;Student&gt; students = new ArrayList&lt;Student&gt;();
</pre>
<p>We are just using a simple JAXB model for the sake of the example which is why we aren&#8217;t including the <code>Teacher</code> and <code>Student</code> classes.
</li>
<li>Now in our <code>CourseService</code> class we will create methods to return the course entity and we will create one for JSON and one for XML.
<pre class="brush: java;">
	@Path(&quot;find/{id}/xml&quot;)
	@GET
	@Produces(MediaType.APPLICATION_XML)
	public Course getCourseAsXml(@PathParam(&quot;id&quot;) Long id) {
		return courseDao.find(id);
	}

	@Path(&quot;find/{id}/json&quot;)
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public Course getCourseAsJson(@PathParam(&quot;id&quot;) Long id) {
		return courseDao.find(id);
	}
</pre>
</li>
<p><small>(note : At this point, I had to switch to using Hibernate as the JPA provider since JAXB didn&#8217;t like the interface EclipseLink used for proxying the properties. You can do this using the Glassfish update tool).</small><br />
If you redeploy the application and browse to <a href="http://localhost:8080/restwebdemo/rest/course/find/1/json">http://localhost:8080/restwebdemo/rest/course/find/1/json</a> you should be prompted to save a file, or it will display the text, but the content should be something like : </p>
<pre class="brush: plain;">
{&quot;createdOn&quot;:&quot;2010-08-27T16:36:57.015-04:00&quot;,
  &quot;id&quot;:&quot;1&quot;,
  &quot;modifiedOn&quot;:&quot;2010-08-27T16:36:57.015-04:00&quot;,
  &quot;title&quot;:&quot;Computing for Beginners&quot;,
   &quot;code&quot;:&quot;CS101&quot;}
</pre>
<p>or if you go to <a href="http://localhost:8080/restwebdemo/rest/course/find/1/xml">http://localhost:8080/restwebdemo/rest/course/find/1/xml</a> you will get an XML version :</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;
&lt;course&gt;
	&lt;createdOn&gt;2010-08-27T16:36:57.015-04:00&lt;/createdOn&gt;
	&lt;id&gt;1&lt;/id&gt;
	&lt;modifiedOn&gt;2010-08-27T16:36:57.015-04:00&lt;/modifiedOn&gt;
	&lt;title&gt;Computing for Beginners&lt;/title&gt;
	&lt;code&gt;CS101&lt;/code&gt;
&lt;/course&gt;
</pre>
<p>Now we can grab objects from our web service, we should look at creating objects from the service. We add a new method that takes the title and code values, creates a new <code>Course</code> with those values and saves it using the <code>courseDao</code>.</p>
<pre class="brush: java;">
	@Path(&quot;create&quot;)
	@PUT
	@Produces(MediaType.APPLICATION_JSON)
	public Course createCourse(@FormParam(&quot;title&quot;) String title,@FormParam(&quot;code&quot;) String code) {
		Course course = new Course();
		course.setTitle(title);
		course.setCode(code);
		courseDao.save(course);
		return course;
	}
</pre>
<p>Here I&#8217;ve used the <code>FormParam</code> annotations to plug form values into the method call. You&#8217;ll notice that using REST conventions, the method to create a course uses the PUT type of request. Now let&#8217;s create a page to enter a title and code and create the course. Notice that our method returns the created course so we can return the course back to the user. This is probably not ideal, but suits for the purposes of demonstration. Now lets create a new HTML page to allow for data entry and calling the web service to create the Course.</p>
<pre class="brush: xml;">
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Insert title here&lt;/title&gt;
&lt;script type=&quot;text/javascript&quot;
	src=&quot;http://localhost:8080/restwebdemo/jquery-1.4.min.js&quot;&gt;
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div id=&quot;message&quot;
	style=&quot;display: none; background: #d0d0f0; padding: 12px&quot;&gt;Message Div&lt;/div&gt;
&lt;form action=&quot;rest/course/create&quot; method=&quot;POST&quot;&gt;

    &lt;fieldset&gt;
    	&lt;legend&gt;Create Course&lt;/legend&gt;
    	&lt;p&gt;
	        Title&lt;br /&gt;
    	    &lt;input id=&quot;title&quot; /&gt;&lt;br /&gt;
    	&lt;/p&gt;
    	&lt;p&gt;
        	Code&lt;br /&gt;
        	&lt;input id=&quot;code&quot; /&gt;&lt;br /&gt;
    	&lt;/p&gt;
    	&lt;input type=&quot;submit&quot; id=&quot;submit&quot; /&gt;
	&lt;/fieldset&gt;
&lt;/form&gt;
&lt;/body&gt;

&lt;script type=&quot;text/javascript&quot;&gt;

//jquery pieces
$(document).ready(function() {

    //change the submit button behaviouus.
    $('#submit').click(function () {
		var title = $(&quot;input#title&quot;).val();
		var code = $(&quot;input#code&quot;).val();

		params = &quot;title=&quot;+title+&quot;&amp;code=&quot;+code;
		//alert(&quot;posting form : &quot;+data);
        $.ajax({
               type: &quot;PUT&quot;,
               url: &quot;rest/course/create&quot;,
               data: params,
               success: function(result) {
        		   showMessage(&quot;Created Course &quot;+result.title+&quot; with id &quot;+result.id+&quot; on &quot;+result.createdOn);
               }
        });
		return false;
    });
});

function showMessage(msg) {
	  $('#message').html(msg);
	  $('#message').fadeIn('fast');
	   $('#message').delay(3000).fadeOut('slow');
}
&lt;/script&gt;
&lt;/html&gt;
</pre>
<p>This looks a lot code, but not really. We import jquery to help us post our form, and we create our form with the two fields. We use JQuery to add an event handler so when you click submit, it packages up the form, calls our web service with a PUT type of request and grabs the returned object as a JSON object, and displays a message using the values from the new instance obtained from the server. To verify that your course has been created, go to the <a href="http://localhost:8080/restwebdemo/home.jsf">front page</a> and you should see it listed.</p>
<p>That about wraps it up for this post, the source code can be downloaded from (<a href='http://www.andygibson.net/blog/wp-content/uploads/2011/03/restwebdemo_pt2.zip'>restwebdemo_pt2</a>), just unzip it, use <code>mvn clean package</code> and deploy the war to glassfish and use the URLs mentioned in the article.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/tutorial/simple-restful-services-in-glassfish-pt-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Binding Dynamic Multi-select Checkboxes with JSF</title>
		<link>http://www.andygibson.net/blog/tutorial/binding-dynamic-multi-select-checkboxes-with-jsf/</link>
		<comments>http://www.andygibson.net/blog/tutorial/binding-dynamic-multi-select-checkboxes-with-jsf/#comments</comments>
		<pubDate>Wed, 27 Oct 2010 13:17:06 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1519</guid>
		<description><![CDATA[This tutorial looks at how JSF makes it easy to create a dynamic list of checkboxes that can be used to select values on the server. Given a list of strings, we want to display the list of values, each with a check box and be able to select or deselect that item from inclusion [...]]]></description>
			<content:encoded><![CDATA[<p>This tutorial looks at how JSF makes it easy to create a dynamic list of checkboxes that can be used to select values on the server.</p>
<p>Given a list of strings, we want to display the list of values, each with a check box and be able to select or deselect that item from inclusion in the selected set.  We want to do it without having to manually add each checkbox to the page and bind it to a property on the backing bean.<br />
<span id="more-1519"></span><br />
JSF controls can be bound to a value in a map using the syntax <code>#{some.map['someKey']}</code> where <code>someKey</code> can also be an EL expression. This means we can bind a checkbox to a Boolean value in the map. If we have an iterable list of of key values, we can bind multiple checkboxes to different values in a map.</p>
<ol>
<li>Create a new backing bean called <code>FormBean</code> with the following code :</p>
<pre class="brush: java;">
public class FormBean {

	private List&lt;String&gt; items;

	private Map&lt;String,Boolean&gt; checkMap = new HashMap&lt;String,Boolean&gt;();

	public FormBean() {
		items = new ArrayList&lt;String&gt;();
		items.add(&quot;Open&quot;);
		items.add(&quot;Closed&quot;);
		items.add(&quot;Pending&quot;);
		items.add(&quot;Suspended&quot;);
		items.add(&quot;In Progress&quot;);
		items.add(&quot;Rejected&quot;);

		//fill the check map with the items defaulted to unchecked
		for (String item : items) {
			checkMap.put(item,Boolean.FALSE);
		}
	}

	public List&lt;String&gt; getItems() {
		return items;
	}

	public Map&lt;String, Boolean&gt; getCheckMap() {
		return checkMap;
	}

}
</pre>
<p>This creates our list of items and populates it with a set of values. The <code>checkMap</code> will be used to track which items are selected and which are not.  The map contains a set of String,Boolean pairs.
</li>
<li>Add one more method to return a string telling us which items are selected
<pre class="brush: java;">
	public String getSelected() {
		String result = &quot;&quot;;
		for (Entry&lt;String,Boolean&gt; entry : checkMap.entrySet()) {
			if (entry.getValue()) {
				result = result + &quot;, &quot;+entry.getKey();
			}
		}
		return result.length() == 0 ? &quot;&quot; : result.sub string(2);
	}
</pre>
<p>To get the list of selected items, we iterate through the set of entries and if the value in the map is true, then it is selected and added to the result string.
</li>
<li>Our backing bean is complete, now we will create our view
<pre class="brush: xml;">
&lt;h:form&gt;
	&lt;h:outputText value=&quot;Currently Selected : #{formBean.selected}&quot; /&gt;

	&lt;ui:repeat var=&quot;item&quot; value=&quot;#{formBean.items}&quot;&gt;
		&lt;h:outputText value=&quot;#{item}&quot; /&gt;
		&lt;h:selectBooleanCheckbox value=&quot;#{formBean.checkMap[item]}&quot;/&gt;
	&lt;/ui:repeat&gt;

	&lt;h:commandButton value=&quot;Update&quot; action=&quot;refresh&quot; /&gt;
&lt;/h:form&gt;
</pre>
<p>We iterate through the list of items and for each one, display the caption (the item itself) and a checkbox bound to the Boolean <code>checkMap</code> entry for that item.</p>
<div class="contentBox alignCenter">
<a href="http://localhost/wordpress/wp-content/uploads/2010/09/JSFCheckMapScreen.png"><img src="http://localhost/wordpress/wp-content/uploads/2010/09/JSFCheckMapScreen-300x257.png" alt="JSF CheckBox Map Screenshot" title="JSF CheckBox Map Screenshot" width="300" height="257"  /></a>
</div>
</ol>
<p>Unfortunately, we can&#8217;t iterate through the <code>keySet</code> because JSF doesn&#8217;t provide for iteration over Sets (next version JSF Expert Group!) so we have to use a separate list as our key. However, this is a nice way of providing a dynamic set of checkbox controls that are bound to dynamic values without having to use any tricks to keep track of control bindings.</p>
<p>If you want to make the list update when you click an item, just add the <code>f:ajax</code> tag to the checkbox like so : </p>
<pre class="brush: xml;">
&lt;h:selectBooleanCheckbox value=&quot;#{formBean.checkMap[item]}&quot;&gt;
	&lt;f:ajax event=&quot;click&quot; execute=&quot;@form&quot; render=&quot;@form&quot; /&gt;
&lt;/h:selectBooleanCheckbox&gt;
</pre>
<p>You can download the working code for this example (<a href='http://www.andygibson.net/blog/wp-content/uploads/2010/09/JsfCheckMap.zip'>JsfCheckMap Demo Source Code</a>) which you can run by unzipping it and in a command line running <code>mvn jetty:run</code> or windows users can just double click <code>run.bat</code>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/tutorial/binding-dynamic-multi-select-checkboxes-with-jsf/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Releasing Maven Projects with Git(Hub) in Windows</title>
		<link>http://www.andygibson.net/blog/tutorial/releasing-maven-projects-with-github-in-windows/</link>
		<comments>http://www.andygibson.net/blog/tutorial/releasing-maven-projects-with-github-in-windows/#comments</comments>
		<pubDate>Wed, 06 Oct 2010 12:38:12 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[GitHub]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Journeyman]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1563</guid>
		<description><![CDATA[In the process of moving some new and existing projects to GitHub and releasing them using Maven under Windows, I discovered a number of issues that can be tricky to get around. This post is for anyone else with the same problems, and for my own future reference. First off, most of these issues are [...]]]></description>
			<content:encoded><![CDATA[<p>In the process of moving some new and existing projects to GitHub and releasing them using Maven under Windows, I discovered a number of issues that can be tricky to get around. This post is for anyone else with the same problems, and for my own future reference. </p>
<p>First off, most of these issues are Windows related and while I would love to move to Linux and be rid of these problems, its impractical at the moment. Also, if you are a non-Windows user you can still get an idea of what is needed to deploy GitHub projects with Maven.</p>
<p>To avoid a disappointing end to the post, the one problem I couldn&#8217;t resolve was releasing multi-module projects with maven. I am still getting the <a href="http://jira.codehaus.org/browse/SCM-547?page=com.atlassian.jira.plugin.system.issuetabpanels%3Aall-tabpanel">StringIndexOutOfBounds error with msysgit</a>. These instructions are still good for single module deployments though. If anyone has a solution to the string index issue, feel free to post in the comments or <a href="http://www.andygibson.net/blog/contact-me/">drop me a line</a>.</p>
<p>My go to page for remembering how to do release a project with Maven is the <a href="https://docs.sonatype.org/display/Repository/Sonatype+OSS+Maven+Repository+Usage+Guide">Sonatype instructions</a> which covers setting up a Sonatype account and tells you what you need to put in your <code>pom.xml</code> file for it to be released automatically.</p>
<p>If you have done maven releases before with subversion, you will know how easy it is. Once the SCM information is in your pom file, Maven will download the source, tag it to the version you select, commit the tag, build it, and deploy it which is really quite nice as well as updating your development code to the new snapshot version.<br />
If you haven&#8217;t done a Maven release before, you will need to set up a PGP key on your machine and post it on a key server (see the Sonatype instructions for more info and links that help).</p>
<p>So at this point, lets assume you have a project ready for release in GitHub (or any other Git repository I guess). You have a PGP key set up on your local machine and added to a public key server. Windows users should also have mSysGit set up, which you probably have if you are developing with Git. Your project should also have the release and deployment information set up as defined in the Sonatype document.</p>
<p>I&#8217;ve seen a  number of different ways of putting the SCM information in the pom file. Here&#8217;s what I used that worked for me. Obviously you&#8217;ll need to change the account name.</p>
<pre class="brush: xml;">
&lt;scm&gt;
   &lt;connection&gt;scm:git:git://github.com/andygibson/${project.artifactId}.git&lt;/connection&gt;
   &lt;url&gt;http://github.com/andygibson/${project.artifactId}&lt;/url&gt;   &lt;developerConnection&gt;scm:git:git@github.com:andygibson/${project.artifactId}.git&lt;/developerConnection&gt;
 &lt;/scm&gt;
</pre>
<p>Interestingly enough, when I was looking to see what other people were using, there are plenty of projects that still have subversion repositories in their scm information. I guess they probably haven&#8217;t changed it over yet because they haven&#8217;t done a release.</p>
<h1>Roadblocks</h1>
<p>There are two main problems that you will hit when releasing with Maven under Windows. The first is that when Maven tries to push the changes back to the Git repository it hangs waiting for the pass phrase for your GitHub SSH key. However, since it never displays a prompt for it, you are stuck waiting for it.</p>
<p>The second problem is exposing your pgp keys to your Git Bash shell. The shell expects the keys to be in a particular folder which doesn&#8217;t exist by default (<code>/c/.gnugp</code>). </p>
<h1>Setting up SSH-Agent</h1>
<p>Start up the Git Bash session (or as OSX and Linux users call it, a shell) and go to your project directory.<br />
Windows users, you need to start up an SSH agent to provide your passkey when needed by the release process.</p>
<p>To do this, in your Git Shell type  :</p>
<pre class="brush: plain;">
eval `ssh-agent`  //pay attention to the back tick quotes here
</pre>
<p>which should return a piece of text like <code>Agent pid xyz</code>. This command starts the agent and sets up a couple of environment variables relating to the SSH agent. If you type <code>env | grep SSH</code> you will see the environment variables :</p>
<pre class="brush: plain;">
$ env | grep SSH
SSH_AGENT_PID=1234
SSH_AUTH_SOCK=/tmp/ssh-abcdef1234/agent.5678
</pre>
<p>Windows users will need to manually create the directory <code>c:/tmp/ssh-abcdef1234/agent.5678</code> otherwise you get and error saying <code>could not open a connection to your authentication agent</code>.<br />
Create the new directory and then add your key to the agent using the following syntax which assumes your Github RSA key is in the <code>c:\.ssh\</code> directory. If it isn&#8217;t then just substitute the directory for your key.</p>
<pre class="brush: plain;">
$ssh-add &quot;/c/.ssh/id_rsa&quot;
enter passphrase :
</pre>
<p> Once you enter the pass phrase, it will be stored for that particular key for the rest of the session. When Git requires the phrase as part of the release it will automatically receive it from the agent.</p>
<p>Note that this set up is only good for the current session. If you open another session and want to do a release in that session, you will need to repeat these steps. I also think it would be a bad idea (or at least pointless) to set up the SSH_AGENT_PID or the SSH_AUTH_SOCK environment variables in any global variables.</p>
<p>So now we have that set up, you should be able to run the <code>mvn release:prepare</code> part of the release. This will grab the source code, update the pom version  and push the changes back to the repository. </p>
<h1>Exposing your PGP keys</h1>
<p>For the next step, (<code>mvn release:perform</code>) we need to do the actual release which involves building the artifacts, signing them and uploading them. I&#8217;m assuming that you already have a project and environment that is correctly configured for release (including the release servers in <code>settings.xml</code>). If not, again, take a look at the Sonatype instructions for info on this. </p>
<p>The problem we&#8217;ll encounter here is that when signing the artifacts, the maven gpg signing plugin can&#8217;t find the keys from the Git Shell. It is looking in the <code>/c/..gnupg</code> directory while the windows version of gpg puts it in the users Application Data folder in their profile. There are two ways to solve this problem, and both involve locating the directory containing the Gnugpg keys. This folder is likely to be <code>My Documents\Application Data\</code> which happens to be a hidden folder for many and varies in location depending on the version of windows. However, in that folder is the <code>gnupg</code> folder that contains your keys. The other piece of the puzzle is the GNUPGHOME environment variable in both Windows and Bash which points to the folder containing the keys.  </p>
<p>You can either move the windows folder to where the Bash shell expects it, and set the Windows environment variable to point to it which means that if you fix it now, it will be fixed for every session. Windows GPG will find the folder through the GNUPGHOME environment variable and Bash will find it because that is the default place it looks for it.</p>
<p>Alternatively, you can leave the folder alone and set the environment variable in the Git shell to point to the key folder where it is. The only problem with this is that the environment variable will need to be set up each time. However, it leaves the rest of your environment alone.</p>
<p>I guess the third option is if you don&#8217;t have a GPG key already set up and are using the Git shell to generate one, you might have to manually create the <code>/c/.gnupg</code> folder manually.</p>
<p>I wanted to move the folder anyway so I went for option one. The choice is up to you, but if you get a message like :</p>
<pre class="brush: plain;">
gpg: no default secret key:secret key not available
pgp: signing failed: secret key not available
</pre>
<p>Its because Gnupg can&#8217;t locate the keys you (should have) already set up.</p>
<p>Once I got that these two problems fixed things went fairly smoothly, well, very smoothly in fact, it just worked. Now, hopefully you won&#8217;t have the same problems I had!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/tutorial/releasing-maven-projects-with-github-in-windows/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>CDI Conversations part 2</title>
		<link>http://www.andygibson.net/blog/tutorial/cdi-conversations-part-2/</link>
		<comments>http://www.andygibson.net/blog/tutorial/cdi-conversations-part-2/#comments</comments>
		<pubDate>Tue, 21 Sep 2010 13:07:43 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Apprentice]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Conversation]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JSF]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1279</guid>
		<description><![CDATA[This article will look at using the Conversation scope defined in JSR 299 (Java Contexts and Dependency Injection), and released as part of Java EE 6. For now, we&#8217;ll stick to non-data driven examples as we explore the ins and outs of the Conversation scope. We&#8217;ll finish up by creating a workspace manager so we [...]]]></description>
			<content:encoded><![CDATA[<p>This article will look at using the Conversation scope defined in JSR 299 (Java Contexts and Dependency Injection), and released as part of Java EE 6. For now, we&#8217;ll stick to non-data driven examples as we explore the ins and outs of the Conversation scope. We&#8217;ll finish up by creating a workspace manager so we can list all the active conversations and switch between them.<br />
<span id="more-1279"></span><br />
A Conversation is like a numbered bucket in the session that exists until either the end of the users session, the conversation times out, or the server side code deliberately ends the conversation. The benefits of a conversational scope are many, letting us easily create pages that can be opened in multiple tabs without having to juggle the state on the client without filling the session with data that will last as long as the user session should we forget to remove it.</p>
<p>We&#8217;ll start by creating a project from the <a href="http://www.andygibson.net/blog/projects/knappsack" target="_blank">knappsack</a><code>jee6-servlet-basic</code>  archetype. This gives us all the features of Java EE 6 without too much code to get in the way.  We&#8217;ll start by creating a backing bean that is request scoped and looking at how that is used and what effect request scope has.</p>
<pre class="brush: java;">
import java.io.Serializable;

import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

@Named(&quot;bean&quot;)
@RequestScoped
public class BackingBean implements Serializable {

	private Long value = new Long(0);

	public Long getValue() {
		return value;
	}

	public void setValue(Long value) {
		this.value = value;
	}

        public String getMessage() {
            return &quot;The value is : &quot;+value;
        }
}
</pre>
<p>Simple enough, now lets add a page called <code>listEdit.xhtml</code>that lets us enter the value, post the value back and see what the message is. </p>
<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;
	template=&quot;/WEB-INF/templates/template.xhtml&quot;&gt;
	&lt;ui:define name=&quot;content&quot;&gt;
		&lt;h:form id=&quot;form&quot;&gt;
            Value : &lt;h:inputText value=&quot;#{bean.value}&quot; /&gt;
			&lt;h:commandButton value=&quot;Submit Value&quot; action=&quot;submit&quot; /&gt;
			&lt;br /&gt;
			&lt;br /&gt;
            Message : #{bean.message}
   &lt;/h:form&gt;

	&lt;/ui:define&gt;
&lt;/ui:composition&gt;
</pre>
<p>Edit <code>home.xhtml</code> to include a link to this page :</p>
<pre class="brush: xml;">
&lt;a href=&quot;listEdit.jsf&quot;&gt;Start New List&lt;/a&gt;
</pre>
<p>Open up the home page and click the link to go to the <code>listEdit</code> page. If we enter a value in the input box and click the submit button, predictably, our message says that the value is whatever we entered.</p>
<div class="contentBox alignCenter">
<img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/request_scoped_bean1.png" alt="Request Scoped Bean Entry Screenshot" title="Request Scoped Bean Entry Screenshot" width="578" height="302" class="alignnone size-full wp-image-1285" />
</div>
<p>What is happening here is that when the form is posted back, the value in the input box is sent back to the <code>bean.value</code> attribute. When the page is rendered back to the user and the message is rendered, it is rendered using this value that we passed back to the server. We pass the state of the attribute from the server to the client, and then back to the server, and we can do that all day long using just the request scope without any problems. This is a stateless page and doesn&#8217;t require any state to be held on the server.</p>
<p>Let&#8217;s add something a bit more stateful to the page such as a list of values that we have added previously. In our backing bean, add the following field and getter method and a method to add the value.</p>
<pre class="brush: java;">
private List&lt;Long&gt; values = new ArrayList&lt;Long&gt;();
..
..
..
public List&lt;Long&gt; getValues() {
	return values;
}

public void addToList() {
	values.add(value);
}
</pre>
<p>Now we will add the list of values to our page to be displayed.</p>
<pre class="brush: xml;">
&lt;ui:define name=&quot;content&quot;&gt;
	&lt;h:form id=&quot;form&quot;&gt;
		Value : &lt;h:inputText value=&quot;#{bean.value}&quot; /&gt;
		&lt;h:commandButton value=&quot;Submit Value&quot; action=&quot;#{bean.addToList}&quot; /&gt;
		&lt;br /&gt;
		&lt;br /&gt;
		Message : #{bean.message}
		&lt;h2&gt;Added Values&lt;/h2&gt;
		&lt;ui:repeat var=&quot;v_value&quot; value=&quot;#{bean.values}&quot;&gt;
			#{v_value}&lt;br /&gt;
		&lt;/ui:repeat&gt;
	&lt;/h:form&gt;
&lt;/ui:define&gt;
</pre>
<p>If we refresh our page, enter a number and click submit, you will see that the number appears at the bottom of the page where it should. When we click the submit button on the form the value is assigned to the <code>value</code> attribute. When the <code>addToList</code> method is called, the <code>value</code> attribute is added to the list. When the page is rendered, the latest value is used to generate the message and for the list of items we return the list containing one item, the new value.</p>
<p>So far so good. Let&#8217;s enter a new number and add it to the list. When we click the button the second time, the only number in the list of numbers is the one we just entered. The first value is gone! The problem is that the second time we posted the value the bean was re-constructed from scratch and had no idea whatsoever about the first value we added to the list. There was nothing on the form to tell the bean about the first number even though we displayed it on the page. The backing bean keeps forgetting our list of numbers from one request to the next, or in other words, our application is missing some state.</p>
<p>As per part 1, there are a number of ways we can get around this problem. We could save the list to the database each time we post, which is over kill for this simple task.   We could push the state down to the client, say using a comma delimited list of existing numbers pushed into a hidden field. When the form is posted, the comma delimited list is sent back to the server where the numbers are unpacked and the list is rebuilt on the server side and the state is restored.<br />
Both of these two methods are doable but what happens when we have more information on the server that we need to keep hold of? Do we have to keep adding add each piece of information to the client state manually, including passing it around from one page to the next for multi-page processes? What if it is a list of entity objects we want to hold on to? Do we just save the Ids on the client and keep re-loading them from the database each time?<br />
These solutions are impractical from the perspective of building a maintainable app quickly. However, note that these solutions are completely possible with JSF and CDI. It just offers better alternatives, but the opportunity to get under the hood and use more lower level solutions in the interests of optimizing the application are always there.  This is an important factor since if you have a widely used conversational page that is creating a bottle neck, you can refactor it down to use a more stateless approach. </p>
<p>Since this article is all about conversations, obviously, we are going to solve our problems using the conversation scope. We will change our bean to be <code>@ConversationScoped</code> and <code>@Inject</code> a <code>Conversation</code> instance we&#8217;ll be using. We&#8217;ll then start the conversation for the page when our bean is constructed. This is an example and typically you don&#8217;t start conversations in bean construction but it serves our purpose here.<br />
<small><b>Tip</b> : Conversations are typically started at specific points on certain initialization methods, starting it on bean construction is bad because you never know when another task might use an instance of that bean</small></p>
<pre class="brush: java;">

@Named(&quot;bean&quot;)
@ConversationScoped
public class BackingBean implements Serializable {
	...
	...
	...
	@Inject
	private Conversation conversation;
	...
	...
	@PostConstruct
	public void postConstruct() {
		conversation.begin();
	}

	public Conversation getConversation() {
		return conversation;
	}
	...
	...
}
</pre>
<p>Reload our page and you can see how you can enter and submit as many numbers as you want to the page and the list state is managed.</p>
<div class="contentBox alignCenter">
<a target="_blank" href="http://www.andygibson.net/blog/wp-content/uploads/2010/08/conv_2_num_list.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/conv_2_num_list-300x248.png" alt="Conversation Number List Screenshot" title="Conversation Number List Screenshot" width="300" height="248" /></a>
</div>
<p>Conversations are just a natural extension of the existing scopes in current web applications. They also become very natural to use. Let&#8217;s add another page that lets us review our list of numbers before &#8216;confirming&#8217; them. Add the following new button at the bottom of our page : </p>
<pre class="brush: xml;">
	&lt;h:commandButton action=&quot;review&quot; value=&quot;Review Numbers&quot;/&gt;
</pre>
<p>Because the <code>action</code> attribute is set to <code>review</code> we will create a new page called <code>review.xhtml</code> that will display the numbers. Our first concern obviously is &#8216;where does it get the list of numbers from?&#8217;, well the answer is, from the same place it got the numbers from last time, using the expression <code>#{bean.values}</code>.</p>
<p><code>review.xhtml</code></p>
<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;
	template=&quot;/WEB-INF/templates/template.xhtml&quot;&gt;
	&lt;ui:define name=&quot;content&quot;&gt;
		&lt;h:form id=&quot;form&quot;&gt;
			&lt;h1&gt;Please Confirm The Values : &lt;/h1&gt;
			&lt;h2&gt;Added Values&lt;/h2&gt;
			&lt;ui:repeat var=&quot;v_value&quot; value=&quot;#{bean.values}&quot;&gt;
			#{v_value}&lt;br /&gt;
			&lt;/ui:repeat&gt;
			&lt;h:commandButton action=&quot;#{bean.confirm}&quot; value=&quot;Confirm&quot;/&gt;
		&lt;/h:form&gt;
	&lt;/ui:define&gt;
&lt;/ui:composition&gt;
</pre>
<p>The way to think about this is to imagine what happens when the page is rendered. JSF will look for the value <code>beans.values</code> which the CDI implementation can provide. Since this page is being rendered in an active conversation, CDI will look in the active conversation &#8216;bucket&#8217; for a bean called <code>bean</code>. Since we are coming from the page that adds the numbers, this bean will already exist in the conversation and so the same instance is returned. Should we render this page without an active conversation, by typing in the URL manually, the page will render, but this time, the instance of <code>beans.xml</code> will not already exist and so CDI will create a new instance of it that doesn&#8217;t contain any items.<br />
<small><b>Tip : </b>There are ways to prevent pages rendering without an active conversation which can also help with duplicate form submissions</b></small></p>
<p>Getting back to the page, we just want to add our confirm method to our backing bean. This method ends the conversation and redirects to the home page which is going back to the number entry page. </p>
<pre class="brush: java;">
public void confirm() {
	conversation.end();
	try {
		FacesContext.getCurrentInstance().getExternalContext().redirect(&quot;home.jsf?faces-redirect=true&quot;);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
</pre>
<p>Add the following at the top of either the review or list edit page to see the conversation Id you are currently in : </p>
<pre class="brush: xml;">
Conversation : #{bean.conversation.id}
</pre>
<p>If you run the application, you can add numbers and when you click review, you get a list of all the numbers you just entered on a separate page.</p>
<div class="contentBox alignCenter">
<a target="_blank" href="http://www.andygibson.net/blog/wp-content/uploads/2010/08/conv_2_num_confirm.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/conv_2_num_confirm-300x260.png" alt="Conversational Number Confirmation" title="Conversational Number Confirmation" width="300" height="260" /></a>
</div>
<p>If we were managing state ourselves, we would have to pass something to the review page to let is know what the list of numbers was, either a database row key, or the comma delimited values. Again, the more state you have to pass around the less verbose and maintainable the application becomes.  CDI is automatically passing our key (the conversation id) around for us. Under the review button the list edit page, add the following GET link :</p>
<pre class="brush: xml;">
&lt;h:link outcome=&quot;review&quot; value=&quot;Review&quot;/&gt;
</pre>
<p>If you look at the link URL it is <code>http://localhost:8080/conversationdemo/review.jsf?cid=xxx</code> where xxx is some number. CDI automatically creates a URL that propagates the conversation for us. If we didn&#8217;t want to propagate the conversation, we can just add a blank <code>cid</code>  parameter and CDI will leave it alone. This can be useful when you want to launch a page without a conversation from a page that is in a conversation. Add the following link : </p>
<pre class="brush: xml;">
&lt;h:link value=&quot;Start New List&quot; target=&quot;_blank&quot;&gt;
	&lt;f:param name=&quot;cid&quot; /&gt;
&lt;/h:link&gt;
</pre>
<p>This lets you start a fresh new list in a separate window (since we didn&#8217;t specify an outcome it defaults to the current page). If you create a new list and add some numbers you can see that you can manage separate lists independently without doing anything to handle multiple browser windows.</p>
<p>When you have multiple windows open, set the url of one window to the url of other (i.e. <code>http://localhost:8080/conversationdemo/listEdit.jsf?cid=xxx</code> where xxx is the other conversation ID) when you load this page, you see the list from the other conversation so you can just switch conversations using GET requests by specifying a different conversation id. </p>
<h1>Workspace Management</h1>
<p>One cool feature of Seam that had a lot of potential was workspace management which lets you see a list of active conversations and select one. We are going to implement a version of that here by providing the user with a set of links that takes us to the active conversation. Create a new bean that is session scoped that will keep a track of our conversation ids.</p>
<pre class="brush: java;">
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

@Named
@SessionScoped
public class WorkspaceBean implements Serializable {

	private List&lt;String&gt; conversations = new ArrayList&lt;String&gt;();

	public List&lt;String&gt; getConversations() {
		return conversations;
	}

}
</pre>
<p>This is just a bean that keeps a list of the conversation Ids currently active. When we start a conversation, we need to add that id to the list and when we end a conversation, we need to remove it from the list. </p>
<p>We will inject this session scoped bean into our backing bean and change the <code>postConstruct</code> and <code>confirm</code> methods in the <code>BackingBean</code> class to add and remove the conversation from the list.</p>
<pre class="brush: java;">
@Inject
private WorkspaceBean workspace;

...
...

@PostConstruct
public void postConstruct() {
	conversation.begin();
	workspace.getConversations().add(conversation.getId());
}

public void confirm() {
	workspace.getConversations().remove(conversation.getId());
	conversation.end();

	try {
		FacesContext ctx = FacesContext.getCurrentInstance();
		ctx.getExternalContext().redirect(&quot;home.jsf?faces-redirect=true&quot;);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
</pre>
<p>Now we need some view code to display the list of conversations and provide links to them. Simply add this to the <code>home.xhtml</code> page, and even the <code>listEdit.xhtml</code> or <code>review.xhtml</code> pages if you want : </p>
<pre class="brush: xml;">
	&lt;h1&gt;Workspaces&lt;/h1&gt;
	&lt;ui:repeat var=&quot;v_conv&quot; value=&quot;#{workspaceBean.conversations}&quot;&gt;
		&lt;h:link outcome=&quot;listEdit&quot; value=&quot;Goto Conversation #{v_conv}&quot;&gt;
			&lt;f:param name=&quot;cid&quot; value=&quot;#{v_conv}&quot; /&gt;
		&lt;/h:link&gt;
		&lt;br /&gt;
	&lt;/ui:repeat&gt;
</pre>
<p>This just loops through the conversations and creates a link to the <code>listEdit</code> page and passes the conversation Id as a parameter. Because we pass a value for <code>cid</code> CDI will not try to add the current conversation as the <code>cid</code> value.</p>
<p>That&#8217;s all you need for a workspace demonstration. You can create new lists and if you jump back to the home page, you will see the available conversations and be able to click the link and jump back into the conversation. When you review the list and confirm it and the conversation ends, when you end up back on the front page, that conversation is longer listed. </p>
<div class="contentBox alignCenter">
<a target="_blank" href="http://www.andygibson.net/blog/wp-content/uploads/2010/08/conv_2_workspace.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/conv_2_workspace-300x235.png" alt="Conversation Workspace Screenshot" title="Conversation Workspace Screenshot" width="300" height="235" class="alignnone size-medium wp-image-1409" /></a>
</div>
<p>This is a fairly powerful mechanism that is built upon the simplicity of CDI Conversations. There is very little work that is required to use conversations, just inject the <code>Conversation</code> instance and call the <code>begin()</code> and <code>end()</code> methods when you need to start and end the conversation. Conversations also have a minimal impact on our code, mainly just an annotation since the getters and settings and other methods don&#8217;t change. We can also easily revert back to a stateless request scoped solution should we have to which would cause additional code to be required to read/write the list to the client.<br />
Conversations should be used with care, especially in terms of making sure you have strict demarcation boundaries, and careful consideration should be given to determining what you include in a conversation.</p>
<p>You can download the maven project source code for this demo (<a href='http://www.andygibson.net/blog/wp-content/uploads/2010/08/conversationdemo.zip'>Conversation Demo </a>), just unzip it and enter <code>mvn jetty:run</code> and navigate to <a href="http://localhost:8080/conversationdemo/home.jsf">http://localhost:8080/conversationdemo/home.jsf</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/tutorial/cdi-conversations-part-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>JSF Basics</title>
		<link>http://www.andygibson.net/blog/tutorial/jsf-basics/</link>
		<comments>http://www.andygibson.net/blog/tutorial/jsf-basics/#comments</comments>
		<pubDate>Wed, 08 Sep 2010 12:51:19 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Apprentice]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[JSF]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1372</guid>
		<description><![CDATA[This is a brief tutorial that takes a quick look at some of the very basics of JSF, how we define pages and hook them up to server side objects. Rather than cover the fundamentals of starting a new JSF application, I&#8217;m going to start from one of the Knappsack archetypes which can provide you [...]]]></description>
			<content:encoded><![CDATA[<p>This is a brief tutorial that takes a quick look at some of the very basics of JSF, how we define pages and hook them up to server side objects. Rather than cover the fundamentals of starting a new JSF application, I&#8217;m going to start from one of the Knappsack archetypes which can provide you with a JEE 6 application ready to roll.  In this case, we are going to start with a servlet based example so you can run it using the embedded servlet containers.<br />
<span id="more-1372"></span><br />
To create the new project, we are going to use the following archetype GAV values. You can also read up  on <a href="http://www.andygibson.net/blog/tutorial/getting-started-with-maven-archetypes/" target="_blank">creating a new Knappsack application</a></p>
<pre class="brush: plain;">
groupId = org.fluttercode.knappsack
artifactId=jee6-servlet-basic
version=1.0.5
</pre>
<p>Once you have your project, just run <code>mvn jetty:run</code> in the command line and navigate to <a href="http://localhost:8080/jsfbasics/home.jsf">http://localhost:8080/jsfbasics/home.jsf</a>. Ok, so now we are up and running, lets look at a JSF page and what it contains.</p>
<p>JSF uses a templating language called facelets. JSF 1 originally used JSP as its view language, but for JSF 2.0 Facelets became the defacto standards and was adopted as the standard view definition languages for JSF 2.0. In our application, we have a template file called <code>WEB-INF/templates/template.xhtml</code>. The template just has a lot of boilerplate view code but there are some <code>ui:insert</code> tags that mark places in the template where we should insert content. For example, the main content is inserted in a facelets area called <code>content</code></p>
<pre class="brush: xml;">
&lt;ui:insert name=&quot;content&quot;&gt;Main Content&lt;/ui:insert&gt;
</pre>
<p>These are insertion points which are used by pages that base themselves on this template. One of the great features of facelets is that the template defines the content points, while the page itself is used to define the template used and then push the content into the content points. This is much better than having to include page fragments in a JSP page, using a page decorator or using a template to include the content page. Our main page <code>home.xhtml</code> is one such page that uses this template. </p>
<p><code>home.xhtml</code></p>
<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;
	template=&quot;/WEB-INF/templates/template.xhtml&quot;&gt;

	&lt;ui:define name=&quot;content&quot;&gt;
		&lt;h1&gt;&lt;h:outputText value=&quot;Hello From JSF&quot; /&gt;&lt;/h1&gt;
	&lt;/ui:define&gt;

&lt;/ui:composition&gt;
</pre>
<p>At the very top, in the composition tag, we tell Facelets that we want to use the file <code>template.xhtml</code> as our template page. Next we have a <code>ui:define</code> tag that defines the content that is to be used in the template. Facelets works by having the page pull the template into the page and pushing its content into the slots provided by the template. This is much better than pulling content into the main page using includes, or specifying a template used everywhere and decorating the content with it. This is the best of both worlds. Each page defines which template page it uses and pushes the content into it. </p>
<h2>Our first used component</h2>
<p>In here you can see we have used our first JSF component : </p>
<pre class="brush: xml;">
&lt;h:outputText value=&quot;Hello From JSF&quot; /&gt;
</pre>
<p>This is a standard JSF component that is used to output text. We could have just written the text right in the page, but the goal of this page is to test that the JSF configuration is working and to do that, we need to see if the JSF component is rendered correctly.  You can edit the text in the value and obviously it will change the text displayed on the page.</p>
<h2>Our first backing bean</h2>
<p>Displaying static text isn&#8217;t what web frameworks were built for, what we really want is to display something that comes from some java code. To do this, we will create a backing bean which is a java object that is part of the web application that JSF is aware of. To create backing bean, create a new class and call it <code>PageBean</code>.</p>
<pre class="brush: java;">
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

@Named
@RequestScoped
public class PageBean {

	private String message = &quot;Mighty apps from little java beans grow&quot;;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
}
</pre>
<p>The code itself is pretty simple. One field with a default value and getters and setters. However, we have a couple of new annotations at the class level. First is the <code>@Named</code> annotation that tells CDI that this bean has a name that be used to refer to this bean using EL expressions. Since we didn&#8217;t supply a name the default name of <code>pageBean</code> is used. The <code>@RequestScope</code> annotation tells CDI that this bean is request scoped so when it is created, it should last till the end of the current request and then be destroyed. This means that the next time we call this page, this bean will be re-created and a fresh version used which again will be destroyed at the end of the request.</p>
<p>Now we are going to change our application to display this message instead.From now on, we will just be showing the code within the <code>ui:define</code> statements:</p>
<pre class="brush: xml;">
	&lt;ui:define name=&quot;content&quot;&gt;
		&lt;h:outputText value=&quot;#{pageBean.message}&quot; /&gt;
	&lt;/ui:define&gt;
&lt;/ui:composition&gt;
</pre>
<p>If we run the application now, you should see the message displayed on the main page:</p>
<div class="alignCenter">
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/08/jsfbasic1_motd.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/jsfbasic1_motd-300x190.png" alt="JSF Basic message of the day screenshot" title="JSF Basic message of the day screenshot" width="300" height="190" /></a>
</div>
<p>Now let&#8217;s take look at a producer method that can be used to display the date and time the page was rendered. First, open up the template file and look for the footer panel at the bottom and change it to :</p>
<pre class="brush: xml;">
&lt;h:panelGroup id=&quot;footer&quot; layout=&quot;block&quot;&gt;This page was rendered at #{currentSysDate}&lt;/h:panelGroup&gt;
</pre>
<p>What is <code>currentSysDate</code> value? Well, we need to go back to our <code>PageBean</code> and define it. We will add a new method that returns a new <code>Date</code> object and we&#8217;ll annotate it with <code>@Named</code> and <code>@Produces</code>. </p>
<pre class="brush: java;">
@Produces @Named(&quot;currentSysDate&quot;)
public Date produceDate() {
	return new Date();
}
</pre>
<p>The <code>Produces</code> and <code>Named</code> annotation tells CDI that this method can be used to produce a value with the name <code>currentSysDate</code>. When our application is deployed, CDI makes a note that this value comes from this method so when our page is rendered and JSF is looking for the value <code>currentSysDate</code>, CDI calls the method and returns the value obtained from this method.</p>
<p>If we refresh the page we can see that our new timestamp function is on there.</p>
<div class="contentBox alignCenter">
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/08/jsfbasic_timestamp.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/jsfbasic_timestamp-300x185.png" alt="JSF Basic Timestamp Screenshot" title="JSF Basic Timestamp Screenshot" width="300" height="185"  /></a>
</div>
<p>This will come in handy later on when we start using AJAX and want to check that the full page has not updated (the timestamp will stay the same because that portion of the page won&#8217;t change). We&#8217;ve shown how we can pull data from the server onto the page so let&#8217;s take a look at how we send data back to the server.</p>
<p>In our <code>home.xhtml</code> page, we&#8217;ll add a text input to edit the message and a button to post it back.</p>
<pre class="brush: java;">
&lt;h:form id=&quot;messageForm&quot;&gt;
	&lt;h:outputText value=&quot;#{pageBean.message}&quot; /&gt;&lt;br/&gt;
	&lt;br/&gt;
	New Message : &lt;h:inputText value=&quot;#{pageBean.message}&quot;/&gt;
	&lt;h:commandButton action=&quot;update&quot; value=&quot;Update&quot;/&gt;
&lt;/h:form&gt;
</pre>
<p>First, we added the <code>h:form</code> tags which gives us an HTML form in which to put input controls. Any data entry in a JSF page needs to be enclosed in a JSF form tag in order to be passed back to the server. We defined an input text box that was bound to the same value as the message display and a command button that is used to post the values back. If we refresh the page, enter a new message and click the button our message changes.</p>
<div class="contentBox alignCenter">
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/08/jsfbasic1_form_post.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/jsfbasic1_form_post-300x184.png" alt="JSF Basic Form Post Screenshot" title="JSF Basic Form Post Screenshot" width="300" height="184"  /></a>
</div>
<p>However, this is the age of Web 2.0, and just posting back a form and displaying the results isn&#8217;t enough, we need to do it with AJAX. AJAX is a mechanism by which the browser makes an asynchronous request to the server and gets a response back. When the response is returned, the browser will call a javascript function that will update part of the page instead of all of it. Sounds complicated, but the nice folks that wrote JSF wrapped all that functionality up in one little tag called <code>f:ajax</code></p>
<p>What we want to do is make our command button an AJAX button which we can do by placing the <code>f:ajax</code> tag as a child tag of the button. All we need to supply the AJAX tag with is the <code>execute</code> and <code>render</code> attributes. This indicates which parts of the page we want to post back to the server, and which parts we want to re-render when the response comes back.  We want to execute the form and re-render the form, so we could use the component id (<code>messageForm</code>) for the attribute values. JSF also provides a couple of shortcuts that we can use. The value <code>@form</code> references the form the button is in so rather than hardcode the form id, the <code>@form</code> value will let us reference the form without doing so by name.</p>
<pre class="brush: java;">
&lt;h:commandButton action=&quot;update&quot; value=&quot;Update&quot;&gt;
	&lt;f:ajax execute=&quot;@form&quot; render=&quot;@form&quot; /&gt;
&lt;/h:commandButton&gt;
</pre>
<p>Notice that now you have an ajax button, the timestamp in the footer doesn&#8217;t change when you post the value back. </p>
<h1>Performing Actions</h1>
<p>So far we have covered displaying information from the server side bean and writing values back, but often we want some user action to execute some code on the server. </p>
<p>Start by adding a <code>Integer</code> attribute on to our <code>PageBean</code> class and two methods, one to increase it, and another to decrease it as well as getters and setters for the value.</p>
<pre class="brush: java;">
	private int value = 0;

	public void increase() {
		value++;
	}

	public void decrease() {
		value--;
	}
</pre>
<p>In the view, we want to display the value and have a couple of buttons to increase and decrease the value. Add the following view code in <code>home.jsf</code> somewhere between the <code>h:form</code> tags :</p>
<pre class="brush: xml;">
&lt;h:panelGroup layout=&quot;block&quot; id=&quot;spinner&quot;&gt;
     &lt;h:commandButton action=&quot;#{pageBean.decrease}&quot; value=&quot;-&quot; /&gt;
     #{pageBean.value}
     &lt;h:commandButton action=&quot;#{pageBean.increase}&quot; value=&quot;+&quot; /&gt;
&lt;/h:panelGroup&gt;
</pre>
<p>Refresh the page and click away, and you&#8217;ll notice something is wrong. Press the increase button and the value goes to 1, click it again and it&#8230;goes to 1. Click the decrease button and it will always go to -1. The problem is an issue of state. Each time we click the button, we post back to the server, and the server creates a new instance of the <code>pageBean</code> and calls the increase or decrease methods. The problem is that each time we create the bean, the value starts at zero and so is only ever increased to 1 or decreased to -1.<br />
Now you may be wondering that since you are displaying the value on the page, isn&#8217;t that enough to post it back to the server, after all, we displayed the message in an input box and it got passed back to the server. The difference is that an input box is known as a JSF value holder, which means it actually holds the value it is bound to on the client and posts it back to the server when the form is posted back. We can see this demonstrated by changing the value text display component to an input text box component:</p>
<pre class="brush: java;">
&lt;h:panelGroup layout=&quot;block&quot; id=&quot;spinner&quot;&gt;
    &lt;h:commandButton action=&quot;#{pageBean.decrease}&quot; value=&quot;-&quot;/&gt;
    &lt;h:inputText value=&quot;#{pageBean.value}&quot;/&gt;
    &lt;h:commandButton action=&quot;#{pageBean.increase}&quot; value=&quot;+&quot; /&gt;
&lt;/h:panelGroup&gt;
</pre>
<p>Now when you click the +/- buttons the value changes beyond -1 and 1. This is because when the page is rendered, the value is stored on the client. When the button is clicked and the form is posted back, the client side value is sent back to the server side attribute and then the increase/decrease method is called with the value that is set. This is fairly common with web forms, and one way of handling state by putting it in client side forms, even as hidden field values.</p>
<p>We can demonstrate this further by manually entering a value into the text input and then clicking a button. Enter 1000 in the input text box and click the increase button. The value should now be 1001. </p>
<div class="contentBox alignCenter">
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/08/jsfbasics1_manual_input.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/jsfbasics1_manual_input-300x184.png" alt="JSF Basics Manual Value Input" title="JSF Basics Manual Value Input" width="300" height="184" /></a>
</div>
<p>When we manually enter a value, we are changing the value held on the client in the value holder represented by the input text box. When we click the increase button we are sending that value back to the server. On postback, the server creates an instance of our <code>PageBean</code> class, sets the value attribute to the value in our text box (1000) and then calls the <code>increase</code> method which increases the value to 1001. Once the method has finished, JSF then must render a response which includes taking the value from the <code>pageBean.value</code> attribute and putting it in our text box which is how the text box shows 1001 after clicking the button. At this point, once our request is complete, the page bean is destroyed as it is only request scoped.</p>
<h2>Validating the value</h2>
<p>If we only want the value to be between 0 and 10, we can add validation annotations onto the value field to enable it to be checked for correctness when we post back the values. In our <code>PageBean</code> class, we&#8217;ll add the annotations as follows : </p>
<pre class="brush: java;">
@Min(value=0)
@Max(value=10)
private int value = 0;
</pre>
<p>We also need some way to display error messages if the user enters an invalid value so we&#8217;ll add a <code>h:message</code> tag. The message tag is used to associate a JSF message with a component and display it. We give the input text box a name and add the message for that component :</p>
<pre class="brush: java;">
&lt;h:panelGroup layout=&quot;block&quot; id=&quot;spinner&quot;&gt;
	  &lt;h:commandButton action=&quot;#{pageBean.decrease}&quot; value=&quot;-&quot;/&gt;
	  &lt;h:inputText value=&quot;#{pageBean.value}&quot; id=&quot;valueInput&quot;/&gt;
	  &lt;h:commandButton action=&quot;#{pageBean.increase}&quot; value=&quot;+&quot; /&gt;
	  &lt;h:message for=&quot;valueInput&quot; styleClass=&quot;errorMessage&quot;/&gt;
&lt;/h:panelGroup&gt;
</pre>
<p> Now refresh the page and enter 1000 into the value text input and click the increase button. You should see an error message next to the text editor because the value is above 10. Try entering the value of -1000 and clicking a button.</p>
<div class="contentBox alignCenter">
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/08/jsfbasic1_input_error.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/jsfbasic1_input_error-300x185.png" alt="JSF Basic Input Error Screenshot" title="JSF Basic Input Error Screenshot" width="300" height="185"/></a>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/tutorial/jsf-basics/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Conversational CRUD in Java EE 6</title>
		<link>http://www.andygibson.net/blog/tutorial/pattern-for-conversational-crud-in-java-ee-6/</link>
		<comments>http://www.andygibson.net/blog/tutorial/pattern-for-conversational-crud-in-java-ee-6/#comments</comments>
		<pubDate>Mon, 30 Aug 2010 13:07:33 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Journeyman]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JSF]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1371</guid>
		<description><![CDATA[This tutorial will demonstrate a pattern for creating CRUD applications in JSF and Java EE 6. While this is not the only way of implementing this mechanism, it does promote re-use and can give you essentially zero code CRUD pages requiring just the view code. The goal is to provide a single structure that provides [...]]]></description>
			<content:encoded><![CDATA[<p>This tutorial will demonstrate a pattern for creating CRUD applications in JSF and Java EE 6. While this is not the only way of implementing this mechanism, it does promote re-use and can give you essentially zero code CRUD pages requiring just the view code. The goal is to provide a single structure that provides the particular feature of being both stateless or conversational where we might want a conversational edit page and a stateless view page. This pattern is based on the <code>EntityHome</code> pattern that was used in JBoss Seam and carries over well to Java EE 6 with CDI. This is something I use all the time to make view/edit pages really quickly and unlike most of the automatic scaffolding in other frameworks, doesn&#8217;t need re-writing to go into production.<br />
<span id="more-1371"></span></p>
<div class="sidenote_right">
<h1>Running in a Servlet Container</h1>
<p>If you are running this in a servlet container or embedded Jetty, you will need to make the following changes :</p>
<ul>
<li>Use the <code>jee6-servlet-sandbox</code> archetype which is only available in Knappsack 1.0.5 upwards.</li>
<li>Remove the <code>@Stateless</code> annotations from the <code>EntityManagerDao</code></li>
<li>Add manual transactions to the entity manager method calls</li>
</ul>
<p>The servlet version of the source code for this project can be downloaded from here (<a href='http://www.andygibson.net/blog/wp-content/uploads/2010/08/crudapp.zip'>Crud App Maven Project Zip</a>).  Just unzip and type <code>mvn jetty:run</code>
</div>
<p>CRUD is an initialism for <strong>C</strong>reate,  <strong>R</strong>etrieve,  <strong>U</strong>pdate,  <strong>D</strong>elete and is applied typically to entity objects or pieces of data in our application. CRUD probably accounts for about 80% of functions in most systems where users enter, update, view and sometimes delete data.</p>
<p>An entity object starts out by being created and then saved to the database. At a later date, the user may want to view the data and then modify and update the data. When the entity is no longer needed, the data will be deleted. This is the long term lifecycle of our data. When an entity is saved, it is saved with a key, or some reference value used to refer to that entity uniquely. Typically, this is an ID field that is often a number. The ID is assigned to the entity when it is saved and used to identify the entity when we want to retrieve, update or delete the entity. </p>
<h1>Create our Application</h1>
<p>We&#8217;ll start by creating a new application using the Knappsack Maven Archetypes. We&#8217;ll use the <code>jee6-sandbox-archetype</code> so we have some data to play with.  Because the Knappsack archetypes are fairly new, you might have problems finding them in your IDEs depending on when you updated from Maven Central, so here is the command line to create the project : </p>
<pre class="brush: plain;">
mvn archetype:generate -DarchetypeGroupId=org.fluttercode.knappsack -DarchetypeArtifactId=jee6-sandbox-archetype -DinteractiveMode=false -DarchetypeVersion=1.0.4 -DgroupId=org.fluttercode.demo -DartifactId=crudapp -Dpackage=org.fluttercode.demo.crudapp
</pre>
<p>You can create the app and then import it into your IDE as needed. We are going to start by creating a very simple DAO style bean that will be used to load, save and refresh objects using the JPA entity manager. We will make it a stateless session bean so that it has transactional capabilities. If you are using the servlet container version, see the sidebar above for necessary changes. The downloadable source code uses the servlet container version so you can run it without an application server.</p>
<ol>
<li>Create a new class called <code>EntityManagerDao</code></li>
<li>Put the following code in the bean
<pre class="brush: java;">
package org.fluttercode.demo.crudapp.bean;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import java.io.Serializable;

import org.fluttercode.demo.crudapp.qualifier.DataRepository;

@Stateless
public class EntityManagerDao implements Serializable {

	@Inject
	@DataRepository
	private EntityManager entityManager;

	public Object updateObject(Object object) {
		return entityManager.merge(object);
	}

	public void createObject(Object object) {
		entityManager.persist(object);
	}

	public void refresh(Object object) {
		entityManager.refresh(object);
	}

	public &lt;T&gt; T find(Class&lt;T&gt; clazz, Long id) {
		return entityManager.find(clazz, id);
	}

	public void deleteObject(Object object) {
		entityManager.remove(object);
	}

}
</pre>
<p>We inject a conversational entity manager into the bean and create methods for create, finding, updating, and removing entities. The <code>DataRepository</code> annotation is a Qualifier that is defined by the archetype and used to access the application&#8217;s default data source.<br />
All this bean really does is provide transaction support on our method calls to the entity manager. It is not a part of the key pattern, just  a mechanism we can use to persist objects transactionally. While this Dao will work for any JPA entity, it is common practice to create Dao objects specific to individual types where you can add helper and additional methods specific to that type.
</li>
</ol>
<h1>Our home bean</h1>
<p>Now we have our support code set up, on to the main feature! We will create a generic home bean that will take an Id and when requested, load the entity bean for that Id. If no Id is available, then we assume a new entity is to be created. Once loaded or created, the entity will be accessible from our JSF pages where we can display or edit the information.</p>
<ol>
<li>Create a new class called <code>org.fluttercode.demo.crudapp.bean.HomeBean</code>. This will be our generic home bean that we use to load and hold our entities.
</li>
<li>Add the following code to make the bean generic and give it an id and entity attribute.
<pre class="brush: java;">
package org.fluttercode.demo.crudapp.bean;

import java.io.Serializable;
import javax.inject.Inject;
import org.fluttercode.demo.crudapp.model.BaseEntity;

public class HomeBean&lt;T extends BaseEntity&gt; implements Serializable {

	@Inject
	private EntityManagerDao entityManagerDao;

	private Long id;
	private T instance;
}
</pre>
<p>Our bean will use the injected <code>EntityManagerDao</code> we just created. The <code>BaseEntity</code> class is a base entity class implemented in the archetype and has the common <code>Id</code> attribute.</li>
<li>Now we want to add the getter method for the instance. What we want to do here is lazy load or create the bean when it is needed. The assumption is that you won&#8217;t request the bean until the home bean has been set up i.e. The id is properly set. The second assumption is that if you request the instance without the Id being set, you are actually creating a new instance.</li>
<li>We&#8217;ll implement this in the getter that calls two other methods, one to create and return a new entity and another to load it. We&#8217;ll also add the getters and setters for the Id.
<pre class="brush: java;">
public T getInstance() {
	if (instance == null) {
		if (id != null) {
			instance = loadInstance();
		} else {
			instance = createInstance();
		}
	}
	return instance;
}

public Long getId() {
	return id;
}
public void setId(Long id) {
	this.id = id;
}
</pre>
</li>
<li>The create or load methods are fairly simply but rely on some reflection magic to get the generic parameter type :
<pre class="brush: java;">
public T loadInstance() {
	return entityManagerDao.find(getClassType(), getId());
}

public T createInstance() {
	try {
		return getClassType().newInstance();
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}

private Class&lt;T&gt; getClassType() {
	ParameterizedType parameterizedType = (ParameterizedType) getClass()
			.getGenericSuperclass();
	return (Class&lt;T&gt;) parameterizedType.getActualTypeArguments()[0];
}
</pre>
</li>
<li>When we edit our entity, we will want to either save the changes, or undo them. We will add two methods to do this, save and cancel and a third utility method called <code>isManaged()</code>.
<pre class="brush: java;">
public boolean isManaged() {
  return getInstance().getId() != null;
}
public String save() {
	if (isManaged()) {
		entityManagerDao.updateObject(getInstance());
	} else {
		entityManagerDao.createObject(getInstance());
	}
	conversation.end();
	return &quot;saved&quot;;
}

public String cancel() {
	conversation.end();
	return &quot;cancelled&quot;;
}
</pre>
<p>We end the conversation when we are done with the data which is when we either save or cancel the changes. Once the conversation is ended, it will be destroyed at the end of the request.
</li>
<li>One last method we want to add is called <code>initConversation</code> that checks to see if we are in a long running conversation, and starts one if we are not. In theory we could put this method anywhere, but here is a good a place as any. We also need to add a <code>Conversation</code> attribute into which we will inject the current conversation.
<pre class="brush: java;">
  	@Inject
  	private Conversation conversation;
  	...
  	...
  	...
	public void initConversation() {
		if (conversation.isTransient()) {
			conversation.begin();
		}
	}
</pre>
</li>
</ol>
<p>This wraps up the coding of our <code>HomeBean</code> that we will use as the backing bean for CRUD pages. Now let&#8217;s try out our new bean by implementing it for our <code>Student</code> entity class and create a page to view and edit our students. </p>
<ol>
<li>Start by creating a new class called <code>org.fluttercode.demo.crudapp.view.StudentHome</code>. We add two class level annotations, one to name the bean so JSF can access it through an EL expression and another to give it a scope. </p>
<pre class="brush: java;">
package org.fluttercode.demo.crudapp.view;

import javax.enterprise.context.ConversationScoped;
import javax.inject.Named;

import org.fluttercode.demo.crudapp.bean.HomeBean;
import org.fluttercode.demo.crudapp.model.Student;

@Named
@ConversationScoped
public class StudentHome extends HomeBean&lt;Student&gt;{

}
</pre>
<p>We subclass the <code>HomeBean</code> and give it our <code>Student</code> class type to tell it what kind of entity we want it to handle. We have given this bean a conversation scope for reasons we&#8217;ll see later.</li>
<li>For our view, create a new page called <code>studentView.xhtml</code> with the following content :
<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:fn=&quot;http://java.sun.com/jsp/jstl/functions&quot;
	template=&quot;/WEB-INF/templates/template.xhtml&quot;&gt;
	&lt;ui:define name=&quot;content&quot;&gt;
		&lt;f:metadata&gt;
			&lt;f:viewParam name=&quot;id&quot; value=&quot;#{studentHome.id}&quot; /&gt;
		&lt;/f:metadata&gt;
		&lt;h:form&gt;
			&lt;h:outputText value=&quot;ID&quot; styleClass=&quot;caption&quot; /&gt;
			&lt;h:outputText value=&quot;#{studentHome.instance.id}&quot; styleClass=&quot;value&quot; /&gt;

			&lt;h:outputText value=&quot;First Name&quot; styleClass=&quot;caption&quot; /&gt;
			&lt;h:outputText value=&quot;#{studentHome.instance.firstName}&quot;
				styleClass=&quot;value&quot; /&gt;

			&lt;h:outputText value=&quot;Last Name&quot; styleClass=&quot;caption&quot; /&gt;
			&lt;h:outputText value=&quot;#{studentHome.instance.lastName}&quot;
				styleClass=&quot;value&quot; /&gt;

			&lt;h:outputText value=&quot;GPA&quot; styleClass=&quot;caption&quot; /&gt;
			&lt;h:outputText value=&quot;#{studentHome.instance.gpa}&quot; styleClass=&quot;value&quot; /&gt;

			&lt;h:link outcome=&quot;studentEdit.jsf&quot; includeViewParams=&quot;true&quot;
				value=&quot;Edit #{studentHome.instance.name}&quot; style=&quot;margin-right : 24px&quot; /&gt;
			&lt;h:link outcome=&quot;studentEdit.jsf&quot; value=&quot;Create Student&quot; /&gt;
		&lt;/h:form&gt;
	&lt;/ui:define&gt;
&lt;/ui:composition&gt;
</pre>
<p>Everything up to the <code>f:metadata</code> tag is boilerplate which includes pulling the template into the page. The <code>f:metadata</code> tag tells JSF to take a parameter called id and put it in the <code>studentHome.id</code> attribute. This is done before the page is rendered as part of our initial setup for the bean so we know which entity to load.</p>
<p>In the view code we bind our text output components to attributes on the instance in the student home bean. We also styled the components so we can alter the display using CSS styles.<br />
At the bottom we have added a couple of links using the new JSF 2.0 <code>h:link</code> component to an as yet unwritten JSF page called <code>studentEdit.xhtml</code>. In the first link, we get JSF to pass in the view parameters automatically which in this case is the student Id value. Our second link is to create a new student which means we call the same <code>studentEdit.xhtml</code> page without passing the id as a parameter which we do by leavinging the <code>includeViewParams</code> attribute set to false.</p>
<p>Note that the <code>h:form</code> tag isn&#8217;t necessary, but will make the next step easier and allow us to add form controls to this form should we want to.
</li>
<li>If you are running JBoss Developer Tools or Netbeans, you should be able to see the <code>Student</code> attributes in the auto-completion (very cool).  If you open this page in a browser with an id (<a href="http://localhost:8080/crudapp/studentView.jsf?id=3">http://localhost:8080/crudapp/studentView.jsf?id=3</a>) you will see the following person displayed :
<div class="contentBox alignCenter">
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/08/crud_pattern_1.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/crud_pattern_1-300x189.png" alt="CRUD Pattern View Screenshot" title="CRUD Pattern View Screenshot" width="300" height="189" /></a>
</div>
<p><small>We did change two of the archetype CSS styles in the file <code>screen.css</code> to the following : </small></p>
<pre class="brush: plain;">
.caption {
	float: left;
	width: 100px;
	padding-top : 2px;
}

.value {
	display : block;
	margin-bottom : 8px;
	margin-right: 8px;
}
</pre>
</li>
</ol>
<p>As you can see, we can display the student details for the given id. The page for editing this person is very similar, so similar in fact that we are going to start by copying the student view page and making 3 line changes and adding a page event.</p>
<ol>
<li>Copy the <code>studentView.xhtml</code> file and paste it in the same folder with the name <code>studentEdit.xhtml</code>. Open it up and make the following changes (highlighted in the source) : </p>
<ul>
<li>Change the <code>outputText</code> components bound to attributes to <code>inputText</code> components. </li>
<li>Add the <code>preRenderView</code> event the the <code>f:metadata</code> tag.</li>
<li>Set the <code>rendered</code> attribute on the ID label and value since new entities don&#8217;t have a value to display</li>
</ul>
<pre class="brush: xml; highlight: [4,5,8,9,12,15,18];">
&lt;ui:define name=&quot;content&quot;&gt;
	&lt;f:metadata&gt;
		&lt;f:viewParam name=&quot;id&quot; value=&quot;#{studentHome.id}&quot; /&gt;
		&lt;f:event type=&quot;preRenderView&quot;
			listener=&quot;#{studentHome.initConversation}&quot; /&gt;
	&lt;/f:metadata&gt;
	&lt;h:form&gt;
		&lt;h:outputText value=&quot;ID&quot; styleClass=&quot;caption&quot; rendered=&quot;#{studentHome.managed}&quot;/&gt;
		&lt;h:outputText value=&quot;#{studentHome.instance.id}&quot; styleClass=&quot;value&quot; rendered=&quot;#{studentHome.managed}&quot;/&gt;

		&lt;h:outputText value=&quot;First Name&quot; styleClass=&quot;caption&quot; /&gt;
		&lt;h:inputText value=&quot;#{studentHome.instance.firstName}&quot; styleClass=&quot;value&quot; /&gt;

		&lt;h:outputText value=&quot;Last Name&quot; styleClass=&quot;caption&quot; /&gt;
		&lt;h:inputText value=&quot;#{studentHome.instance.lastName}&quot; styleClass=&quot;value&quot; /&gt;

		&lt;h:outputText value=&quot;GPA&quot; styleClass=&quot;caption&quot; /&gt;
		&lt;h:inputText value=&quot;#{studentHome.instance.gpa}&quot; styleClass=&quot;value&quot; /&gt;

		&lt;h:commandButton value=&quot;Save&quot; action=&quot;#{studentHome.save}&quot; style=&quot;margin-right : 8px&quot; /&gt;
		&lt;h:commandButton value=&quot;Cancel&quot; action=&quot;#{studentHome.cancel}&quot; immediate=&quot;true&quot; style=&quot;margin-right : 8px&quot; /&gt;
		&lt;/h:form&gt;
	&lt;/ui:define&gt;
</pre>
<p>If you launch this page now (<a href="http://localhost:8080/crudapp/studentEdit.jsf?id=3">http://localhost:8080/crudapp/studentEdit.jsf?id=3</a>), you will see that we have an editor filled with the attribute values that can be changed. </p>
<div class="contentBox alignCenter">
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/08/crud_pattern_edit.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/crud_pattern_edit-300x274.png" alt="CRUD Pattern Edit Screenshot" title="CRUD Pattern Edit Screenshot" width="300" height="274" /></a>
</div>
</li>
</ol>
<p>That was pretty easy! The reason being is that we re-used the <code>StudentHome</code> bean in our edit page because it performs the same role in providing the requested entity based on the bean&#8217;s id value. We don&#8217;t need to tell the home bean that it is being used somewhere else because the page pulls the bean into the page.</p>
<h1>Conversational or Not?</h1>
<p>It&#8217;s important to notice that in the view page we do not call the method to initialize the conversation. Conversational beans that are not in a long running conversation are reduced to request scoped because the conversation context is destroyed at the end of the request if it is not marked as long running. This means that our view page is fairly stateless since the <code>StudentHome</code> bean used in this page is effectively request scoped.  This is actually a good thing since when we press the refresh button, the page is regenerated from scratch instead of using an older version of the data held in the conversation.</p>
<p>On the other hand, the edit page does call the <code>initConverstion</code> method which starts a conversation. This means that the edit page is conversational which is good because it carries the state from one request to the next without relying on our page to support that state or having to reload it each time. Without the conversation we would have to manually propagate the id value from one request to the next, and possibly other values that are a part of the entity but not edited on the page. For example, if we had an <code>addedDate</code> attribute, we might want to display it, but not edit it, but without conversations we have to resort to either putting it in a hidden field in the form, or re-loading the object to get the value on postback. Otherwise how can we have the right value when we save the edited entity to the database?</p>
<p>This dual nature of the conversation scope is a very useful feature of CDI (and Seam before it) because it allows one bean to act in two different scopes depending on whether the conversation is long running or not which is ideal for view and edit pages. </p>
<p>This is a simple design that can be re-used anywhere you need to edit an entity with little or no code changes. </p>
<p>You can download the servlet version of the demo project from here (<a href='http://www.andygibson.net/blog/wp-content/uploads/2010/08/crudapp.zip'>Crud App Maven Project Zip</a>). Just unzip it and run <code>mvn jetty:run</code></p>
<h1>Additional Points</h1>
<p>Here are some addition points that are not a core part of the demonstration but flesh things out a bit more. All these changes are included in the maven project that can be downloaded.</p>
<h2>Do we need an Entity Manager DAO?</h2>
<p>Here we used a simple DAO to wrap calls to the EntityManager. There&#8217;s no reason you couldn&#8217;t make your Entity Home bean an EJB, inject the entity manager and persist the entities directly. With a separate entity manager DAO it makes writing code for servlet containers cleaner since the explicit transactions are bundled in the DAO. Also, it is possible to write one DAO bean for Java EE 6 servers and another for Servlet containers and switch between them using <code>@Alternative</code>.</p>
<h2>Deleting is a part of CRUD</h2>
<p>I left deleting out primarily because it is fairly simple and the focus was really on the retrieve and update pieces which is often trickier. To implement delete, we add a method to the <code>HomeBean</code> to end the conversation and delete the item.</p>
<pre class="brush: java;">
public String delete() {
	entityManagerDao.deleteObject(getInstance());
	conversation.end();
	return &quot;deleted&quot;;
}
</pre>
<p>Now we just need to add a button to call the delete method from the edit page.</p>
<pre class="brush: xml;">
&lt;h:commandButton value=&quot;Delete&quot; action=&quot;#{studentHome.delete}&quot;/&gt;
</pre>
<p>When we click the button, we delete the entity, and return the action value &#8220;deleted&#8221; for which, in the next section, we&#8217;ll add navigation to the home page.</p>
<h2>Finding your way around</h2>
<p>We haven&#8217;t included any navigation here so when you save or cancel changes, you stay on the same page. So far I&#8217;ve left it out because it isn&#8217;t central to the CRUDness of the tutorial. However, we can easily add some navigation in <code>faces-config.xml</code>.</p>
<pre class="brush: xml;">
	&lt;navigation-rule&gt;
		&lt;from-view-id&gt;/studentEdit.xhtml&lt;/from-view-id&gt;
		&lt;navigation-case&gt;
			&lt;from-outcome&gt;saved&lt;/from-outcome&gt;
			&lt;to-view-id&gt;/studentView.xhtml&lt;/to-view-id&gt;
			&lt;redirect include-view-params=&quot;true&quot; /&gt;
		&lt;/navigation-case&gt;

		&lt;navigation-case&gt;
			&lt;from-outcome&gt;cancelled&lt;/from-outcome&gt;
			&lt;if&gt;#{studentHome.managed}&lt;/if&gt;
			&lt;to-view-id&gt;/studentView.xhtml&lt;/to-view-id&gt;
			&lt;redirect include-view-params=&quot;true&quot; /&gt;
		&lt;/navigation-case&gt;

		&lt;navigation-case&gt;
			&lt;from-outcome&gt;cancelled&lt;/from-outcome&gt;
			&lt;if&gt;#{!studentHome.managed}&lt;/if&gt;
			&lt;to-view-id&gt;/home.xhtml&lt;/to-view-id&gt;
			&lt;redirect include-view-params=&quot;true&quot; /&gt;
		&lt;/navigation-case&gt;

		&lt;navigation-case&gt;
			&lt;from-outcome&gt;deleted&lt;/from-outcome&gt;
			&lt;to-view-id&gt;/home.xhtml&lt;/to-view-id&gt;
		&lt;/navigation-case&gt;

	&lt;/navigation-rule&gt;
</pre>
<p>Notice that when we cancel the changes, we go to either the view page or the home page depending on whether the entity exists in the database.</p>
<h2>Better Homes</h2>
<p>Let&#8217;s also add on a better home page so you can see and select different students. Add the following method to the <code>DataFactory.java</code> class that comes with the archetype.</p>
<pre class="brush: java;">
	@Produces
	@Named(&quot;students&quot;)
	public List&lt;Student&gt; getStudents() {
		List&lt;Student&gt; students = entityManager.createQuery(
				&quot;select s from Student s&quot;).setMaxResults(20)
				.getResultList();
		return students;
	}
</pre>
<p>Open up the the <code>home.xhtml</code> page and change the content to :</p>
<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:fn=&quot;http://java.sun.com/jsp/jstl/functions&quot;
	template=&quot;/WEB-INF/templates/template.xhtml&quot;&gt;
	&lt;ui:define name=&quot;content&quot;&gt;
		&lt;h1&gt;Courses&lt;/h1&gt;
		&lt;h:form&gt;
			&lt;h:dataTable value=&quot;#{students}&quot; var=&quot;v_student&quot;
				styleClass=&quot;dataTable&quot; rowClasses=&quot;odd,even&quot;&gt;
				&lt;h:column&gt;
					&lt;f:facet name=&quot;header&quot;&gt;Id
				&lt;/f:facet&gt;
				#{v_student.id}
			&lt;/h:column&gt;

				&lt;h:column&gt;
					&lt;f:facet name=&quot;header&quot;&gt;Name
				&lt;/f:facet&gt;
					&lt;h:link outcome=&quot;studentView.jsf?id=#{v_student.id}&quot;
						value=&quot;#{v_student.name}&quot; /&gt;
				&lt;/h:column&gt;

			&lt;/h:dataTable&gt;
		&lt;/h:form&gt;
		&lt;h:link outcome=&quot;studentEdit.jsf&quot; value=&quot;Create Student&quot; /&gt;

	&lt;/ui:define&gt;
&lt;/ui:composition&gt;
</pre>
<p>This will list all the students and let you edit them or add new ones. The project source that can be downloaded (<a href='http://www.andygibson.net/blog/wp-content/uploads/2010/08/crudapp.zip'>Crud App Maven Project Zip</a>) includes these changes plus validation error messages on controls.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/tutorial/pattern-for-conversational-crud-in-java-ee-6/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Create A New Project With Maven Archetypes</title>
		<link>http://www.andygibson.net/blog/tutorial/getting-started-with-maven-archetypes/</link>
		<comments>http://www.andygibson.net/blog/tutorial/getting-started-with-maven-archetypes/#comments</comments>
		<pubDate>Sun, 01 Aug 2010 16:50:12 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Apprentice]]></category>
		<category><![CDATA[Archetypes]]></category>
		<category><![CDATA[eclips]]></category>
		<category><![CDATA[Knappsack]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Netbeans]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1076</guid>
		<description><![CDATA[Prerequisites Install Maven In this tutorial, we will create a new project using the Knappsack Archetypes and compile and deploy it. For this example, we will use the jee6-basic-archetype. Before you begin, you will need to have installed Maven, but you no longer need to manually install the Knappsack Archetypes as they are in the [...]]]></description>
			<content:encoded><![CDATA[<div class="prereq">
<ul>
<lh>Prerequisites</lh></p>
<li>Install Maven</li>
</ul>
</div>
<p>In this tutorial, we will create a new project using the Knappsack Archetypes and compile and deploy it. For this example, we will use the <code>jee6-basic-archetype</code>.  Before you begin, you will need to have installed Maven, but you no longer need to manually install the Knappsack Archetypes as they are in the Central Maven Repository now, so you just need to make sure your index is up to date.  These instructions will work for any Maven Archetype you have installed and creating new maven projects in general.<br />
<span id="more-1076"></span><br />
Maven archetypes can be thought of as templates that are installed into the Maven environment and can be used to generate new applications from scratch that are pre-configured for certain environments, whether it is Java EE 6, Wicket or Spring. We can create our project using either the command line or an IDE and both Eclipse and Netbeans both have support for Maven. Netbeans has it out of the box while Eclipse requires m2Eclipse to be installed. This tutorial covers all three methods of creating projects from Maven.</p>
<h1>New project from the Command Line</h1>
<ol>
<li>Start by opening up a command prompt and navigating to the directory your project will reside in</li>
<li>The easy way to create a project on the command line is to just type
<pre class="brush: plain;">
mvn archetype:generate
</pre>
<p>We will use the easier version where we don&#8217;t have to specify long command lines that include the group and archetype Ids and versions.
</li>
<li> You will be greeted with a long list of possible archetypes with a number next to them and a prompt at the bottom to enter the number of the archetype you want to use.
<pre class="brush: plain;">
4: local -&gt; jee6-minimal-archetype (Minimal Java EE application with a single page demo of CDI, JSF, JPA and Validation to ...
5: local -&gt; jee6-basic-archetype (Basic Java EE application with just configuration for CDI, JSF, JPA and a sample empty page.)
6: local -&gt; jee6-sandbox-archetype (Sandbox project for Java EE 6 with CDI, JSF, JPA and a sample model and test data to play ....
7: local -&gt; jee6-sandbox-demo-archetype (Complete demo example using CDI, JSF, JPA and validation showcasing a number of ...
8: remote -&gt; docbkx-quickstart-archetype (null)
9: remote -&gt; j2me-simple (Maven 2 Archetype for midlet application using j2me-maven-plugin)
10: remote -&gt; vaadin-archetype-clean (This archetype generates a simple Vaadin application as a Maven project...
...
...
...
...
Choose a number: 65:
</pre>
<p>Hint : Your locally installed ones should be near the start of the list. The default number (in this case 65) is the quickstart archetype to produce and empty maven project.
</li>
<li>Enter the number of the Knappsack archetype you want to use and press enter.</li>
<li>You will then be asked to enter a number of different properties for the project :
<pre class="brush: plain;">
Define value for property 'groupId': : com.yourcompany
Define value for property 'artifactId': : yourprojectname
Define value for property 'version': 1.0-SNAPSHOT:
Define value for property 'package': com.yourcompany:
Confirm properties configuration:
groupId: com.yourcompany
artifactId: yourprojectname
version: 1.0-SNAPSHOT
package: com.yourcompany
Y:
</pre>
<p>Here we assumed the version is the default SNAPSHOT version and that the default package is the same as the groupId value.
</li>
<li>Once complete, if you look in the directory you will see a new directory called <code>yourprojectname</code>. Move into this directory and if you have <code>JBOSS_HOME</code> set up you can deploy the project straight away.
<pre class="brush: plain;">
mvn clean package jboss:hard-deploy
</pre>
<p>Start up JBoss if it isn&#8217;t already and go to <a href="http://localhost:8080/yourprojectname/home.jsf">http://localhost:8080/yourprojectname/home.jsf</a>.
</li>
<li>You can now import this project into an IDE such as Eclipse or Netbeans as these IDEs recognize Maven projects</li>
</ol>
<p>Alternatively, you can use the command line to enter one long command, or as I do, put it in a script or batch file that I can edit in a text editor and run it from there. Here&#8217;s an example to get you started which you can copy and paste:</p>
<pre class="brush: plain;">
mvn archetype:generate -DarchetypeGroupId=org.fluttercode.knappsack -DarchetypeArtifactId=jee6-sandbox-demo-archetype -DinteractiveMode=false -DarchetypeVersion=1.0.4 -DgroupId=org.application -DartifactId=sandboxdemo -Dpackage=org.application
</pre>
<h1>Creating a project in an IDE</h1>
<p>Creating a Maven project in an IDE is much easier, although sometimes not by much. Typically, you choose to create a new project in the IDE and select maven as the type of project you want to create. </p>
<h2>Netbeans</h2>
<ol>
<li>Select <em>File->New Project</em> and in the first list, select <em>Maven</em> and on the right hand side, select <em>Maven Project</em> (<b>not</b> <em>Maven Web Application</em>). Click Next.</li>
<li>Here we will pick our archetype to create our application from. In the list, expand the <em>Archetypes from Local Repository</em> item in the list. If you don&#8217;t see the archetypes there, you might need to refresh the index in the IDE. Close the new project window to do this.
<ol>
<li>Select <em>Window->Other->Maven Repository Browser</em> to open the repository browser. </li>
<li>In the repository browser window, right click on the repository and select <em>Update Index</em>.</li>
</ol>
<p>Now you should be able to start the new project from scratch and see the missing archetypes.</p>
<div class="contentBox alignCenter">
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/07/netbeans_select_archetype.png" target="_blank"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/07/netbeans_select_archetype-300x182.png" alt="Netbeans Select Archetype Screenshot" title="Netbeans Select Archetype" width="300" height="182" /></a>
</div>
<p>Once you have selected the archetype, click finish to setup the project properties.
</li>
<li>The project properties are the group and archetype Id for the new project as well as the optional default package name.
<div class="contentBox alignCenter">
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/07/netbeans_project_properties.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/07/netbeans_project_properties-300x156.png" alt="netbeans project properties screenshot" title="netbeans project properties screenshots" width="300" height="156" /></a>
</div>
<p>You will also configure the project location here and click <em>Finish</em> when done.
</li>
<li>Once complete, Netbeans will create your project and open it up.  To run it, click <em>Run->Run Main Project</em> and it will prompt you for a Java EE 6 server to use. Select one and click ok. Remember that you need to change the datasource name in <code>persistence.xml</code> so it is not looking for the JBoss default datasource name. </li>
</ol>
<h2>Eclipse</h2>
<p>First make sure you have m2Eclipse installed and are running Eclipse under a JDK instead of a JRE. For more details see this  <a href="http://www.andygibson.net/tutorial/installing-and-configuring-eclipse/">Installing and configuring Eclipse tutorial</a>.</p>
<ol>
<li>In Eclipse, click on <em>File->New->Other..</em> to bring up the dialog for new projects and start typing &#8220;maven&#8221; in the search box</p>
<div class="contentBox alignCenter">
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/07/eclipse_new_maven_project.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/07/eclipse_new_maven_project-300x186.png" alt="Eclipse New Maven Project Screenshot" title="Eclipse New Maven Project Screenshot" width="300" height="186" /></a>
</div>
<p>Select the maven project item from the list and click <em>Next</em>.
</li>
<li> This page lets you determine where the project will reside. Leave the defaults, but make sure the &#8220;Create simple project&#8221; option is <b>un</b>checked and click <em>Next</em>.</li>
<li>Here we will pick our archetype which in this case is our Knappsack jee6 minimal archetype. Start typing &#8220;knappsack&#8221; in the list and you will see the list of available Knappsack archetypes. Again, it is possible that the IDE&#8217;s index of the local repository is not up to date and needs a refresh. You will need to cancel the project creation window to do this.
<ol>
<li>Select <em>Window->Show View->Other</em> and in the view selection , start typing &#8220;Maven&#8221; until you see the window &#8220;Maven Repositories&#8221;. Select this to open up the view.</li>
<li>In the Maven Repositories view, expand the <em>Local Repositories</em> item and right click click on the <em>Local Repository (pathname)</em> item and select <em>Rebuild Index</em>. Confirm that you want to rebuild the index and wait a few moments.</li>
<li>Restart the project creation and this time you should see the archetypes you are looking for.</li>
</ol>
<div class="contentBox alignCenter">
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/07/eclipse_select_knappsack.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/07/eclipse_select_knappsack-300x268.png" alt="Eclipse Select Archetype" title="Eclipse Select Archetype" width="300" height="268" /></a>
</div>
<p>Select the archetype you want to create and click <em>Next</em>.
</li>
<li>Now we need to enter the project configuration information, what our project is called, give it a group id, version and default package.
<div class="contentBox alignCenter">
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/07/eclipse_project_properties.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/07/eclipse_project_properties-300x268.png" alt="Eclipse new Maven Project Properties" title="Eclipse new Maven Project Properties" width="300" height="268" /></a>
</div>
<p>Once the above information is entered you can click <em>Finish</em> and Eclipse will work away at creating your project
</li>
<li>To run the project, the easiest way is to install a server in Eclipse (see <a href="http://www.fluttercode.com/tutorial/installing-servers-into-eclipse/">Tutorial on adding servers in Eclipse</a>) and add the new project to the server. Start the server and navigate to your main page to see it in action.
</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/tutorial/getting-started-with-maven-archetypes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Installing the Knappsack Archetypes</title>
		<link>http://www.andygibson.net/blog/tutorial/installing-the-knappsack-archetypes/</link>
		<comments>http://www.andygibson.net/blog/tutorial/installing-the-knappsack-archetypes/#comments</comments>
		<pubDate>Sun, 01 Aug 2010 16:43:42 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Archetypes]]></category>
		<category><![CDATA[Knappsack]]></category>
		<category><![CDATA[Maven]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1253</guid>
		<description><![CDATA[This is a brief guide to downloading and installing the Knappsack Maven Archetypes for Java EE 6. Updated &#8211; 12th August 2010 The archetypes are now in the Central Maven Repository so there is no need to manually install them. Download the Knappsack Maven Archetypes from here Unzip the downloaded file into a temporary directory [...]]]></description>
			<content:encoded><![CDATA[<p>This is a brief guide to downloading and installing the Knappsack Maven Archetypes for Java EE 6.<span id="more-1253"></span></p>
<h1>Updated &#8211; 12th August 2010</h1>
<p> The archetypes are now in the Central Maven Repository so there is no need to manually install them. </p>
<ol>
<li>Download the Knappsack Maven Archetypes from <a href="https://github.com/andygibson/knappsack/">here</a> </li>
<li>Unzip the downloaded file into a temporary directory</li>
<li>Open a command prompt and navigate to the directory you unzipped the archetypes to.</li>
<li>In the directory, type the command :
<pre class="brush: plain;">
mvn clean install
</pre>
<p>The archetypes will then be installed and ready for creating new projects.
</li>
<p>To learn more about the archetypes read <a href="http://www.andygibson.net/blog/articles/knappsack-archetypes-part-1/ ">this guide</a>. To see all Knappsack related content, click <a href="http://www.andygibson.net/blog/tag/knappsack/">here</a>.
</ol>
<p>Once you have installed the Knappsack Maven Archetypes you can delete the original source since they have been compiled and installed into your Maven repository.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/tutorial/installing-the-knappsack-archetypes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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 [...]]]></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 [...]]]></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>1</slash:comments>
		</item>
	</channel>
</rss>

