<?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>Xebia Blog &#187; Maarten Winkels</title>
	<atom:link href="http://blog.xebia.com/author/mwinkels/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.xebia.com</link>
	<description>Software development done right!</description>
	<lastBuildDate>Wed, 01 Feb 2012 00:30:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Agile says: Nothing will ever be perfect</title>
		<link>http://blog.xebia.com/2011/09/21/agile-says-nothing-will-ever-be-perfect/</link>
		<comments>http://blog.xebia.com/2011/09/21/agile-says-nothing-will-ever-be-perfect/#comments</comments>
		<pubDate>Wed, 21 Sep 2011 07:00:59 +0000</pubDate>
		<dc:creator>Maarten Winkels</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[barely good enough]]></category>
		<category><![CDATA[learning by doing]]></category>
		<category><![CDATA[perfection]]></category>
		<category><![CDATA[Scrum]]></category>
		<category><![CDATA[TDD]]></category>

	<!-- AutoMeta Start -->
	<category>mistakes</category>
	<category>perfect</category>
	<category>dare</category>
	<category>brave</category>
	<category>perfection</category>
	<category>learns</category>
	<category>gradually</category>
	<category>mistakes</category>
	<category>perfect</category>
	<category>dare</category>
	<category>brave</category>
	<category>perfection</category>
	<category>learns</category>
	<category>gradually</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=7332</guid>
		<description><![CDATA[Wouldn&#8217;t it be sweet if your whole life were perfect? Your wife would fulfill your every wish. Your children would be perfect examples of responsible happy people growing up. At work your colleagues are the nicest people and working with them is always fun. Your team would feel responsible for every action they (proactively) take [...]]]></description>
			<content:encoded><![CDATA[<p><img style="float: right" width="70px" border="0" src="http://images3.wikia.nocookie.net/__cb20061109120654/uncyclopedia/images/1/12/MonaLisa.jpg">Wouldn&#8217;t it be sweet if your whole life were perfect? Your wife would fulfill your every wish. Your children would be perfect examples of responsible happy people growing up. At work your colleagues are the nicest people and working with them is always fun. Your team would feel responsible for every action they (proactively) take and the software systems you produce and maintain are flawless and run like well oiled machines?&#8230;</p>
<p>You need to wake up! Nothing will ever be perfect and Agile knows it!<br />
<span id="more-7332"></span></p>
<h3>Perfection and Change</h3>
<p>How does Agile know this? The answer is very simple: If something was perfect, changing it could only make it worse. Agile says embrace and welcome change and thus acknowledges that nothing will ever be perfect. There will always be room for improvement in (almost) every direction!</p>
<p>In an Agile software project this applies to all possible levels: The code, the design and the architecture will never be perfect. The business requirements will never be perfectly clear. The team and the process require constant attention. Collaboration can always be improved.<br />
That is why Agile processes incorporate finding improvements into their very core. For example, the sole purpose of the retrospective meeting in a SCRUM process is to find concrete ways to improve yourself as a team in every possible direction. The scope of the improvements is limited only by the capabilities of the team: The team is allowed to change and improve every aspect of their way of working, be it how they write code, how they communicate with the rest of the organization or how they schedule their meetings.</p>
<p>Agile goes even further and says that everything should be <a href="http://www.agilemodeling.com/essays/barelyGoodEnough.html">barely good enough</a>. As a software development practice <a href="http://en.wikipedia.org/wiki/Test-driven_development">Test Driven Development</a> embodies this. This approach helps the developer to focus on writing only what is absolutely necessary.</p>
<h3>The Agile answer: Learning by Doing</h3>
<p>So, how do you build good systems in an imperfect world? The agile answer is to see the whole building process as a learning exercise on all levels. The business gradually learns what they really want, while the team learns to work together and how to apply the latest technology to the chose architecture and solve the technical problems. And where people are learning, mistakes<sup><a href="#note_1">1</a></sup> are being made. This is not to be avoided nor to be feared: Making mistakes is the only behavior that infallibly leads to learning.</p>
<p>As a SCRUM team you are in the perfect position to learn from your mistakes, if you allow yourself to make mistakes, dare to look them in the face and only then try to overcome them. SCRUM&#8217;s short iterative process and intensive <b>inspect and adapt</b> cycle will bring out the problems sharp and quickly. It is up to the SCRUM team to be brave and tackle the ever arising problems. And remember, even if you constantly tackle every problem that comes your way&#8230; nothing will.. ever&#8230; be perfect&#8230;</p>
<p>The one thing that is allowed to be perfect is the vision of where you are going. The vision of a beautiful system and a happy team. This vision lives in a perfect world. It will always be that one dot just over the horizon. The prefect image that -you will have to accept- is ever out of reach. The main challenge is to keep the team in the right direction and gently steer it closer and closer.</p>
<h3>Agile pitfall: Single User Story Features</h3>
<p>One approach that aims for perfection and ends with frustration is to try to complete every feature in one go. The iterative approach is meant to enable developers and users to learn. The more opportunities for learning, the more you will learn. So instead of building a feature in one go, and create only one learning moment, deliver in small steps and gradually improve the application.</p>
<p>A good agile planning incorporates this from the beginning and deliberately plans to pickup the same functional area multiple times during the development process. Don&#8217;t try to do the fancy search box all in one go: start with simple searching, add auto complete, add a time filter, add faceting. Make all of these simple improvements small User Stories that you plan over the course of the entire development process.</p>
<h3>Conclusion</h3>
<p>Be brave!<br />
Deliberately take small steps!<br />
Dare to accept the current reality as the only reality!<br />
Dare to dream of the perfect end result!</p>
<p>If you start to take small steps, allow your team to make mistakes and stimulate them to learn from them, you&#8217;ll find that working with them becomes easier and more fun. The team will feel more empowered and more eager to take decisions. Eventually, you&#8217;ll also be happier at home, a better husband and after years and years of applying this rule, you&#8217;ll finally see how your children have grown into responsible adults <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<div style="color: grey;">
<b>Footnotes</b></p>
<ol>
<li><a name="note_1"></a>Mistakes here are not like bugs or coding errors, but rather like misinterpretations or misunderstandings.</li>
</ol>
</div>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2011/09/21/agile-says-nothing-will-ever-be-perfect/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2011%2F09%2F21%2Fagile-says-nothing-will-ever-be-perfect%2F&amp;title=Agile%20says%3A%20Nothing%20will%20ever%20be%20perfect" id="wpa2a_2"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2011/09/21/agile-says-nothing-will-ever-be-perfect/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Master-detail implementation for RESTful services with JQuery</title>
		<link>http://blog.xebia.com/2011/09/15/master-detail-implementation-for-restful-services-with-jquery/</link>
		<comments>http://blog.xebia.com/2011/09/15/master-detail-implementation-for-restful-services-with-jquery/#comments</comments>
		<pubDate>Thu, 15 Sep 2011 15:26:17 +0000</pubDate>
		<dc:creator>Maarten Winkels</dc:creator>
				<category><![CDATA[REST]]></category>
		<category><![CDATA[ria]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[master-detail]]></category>
		<category><![CDATA[rest]]></category>

	<!-- AutoMeta Start -->
	<category>opts</category>
	<category>jquery</category>
	<category>restclient</category>
	<category>doajaxcall</category>
	<category>opts</category>
	<category>jquery</category>
	<category>restclient</category>
	<category>doajaxcall</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=7207</guid>
		<description><![CDATA[In two previous posts, we have seen how to develop RESTful application with JBoss AS 7. At the end of the second blog we used a generic REST client tool to execute some RESTful web services. Of course we would rather build a custom UI application as client for our services, so that a user [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.nicolaslattery.com/" target="_blank"><img style="float: right; margin: 5px;" src="http://www.nicolaslattery.com/mediac/400_0/media/Restful~Flight.jpg" alt="" width="100" height="75" /></a>In two <a href="http://blog.xebia.com/2011/07/developing-restful-applications-on-jboss-as-7/">previous</a> <a href="http://blog.xebia.com/2011/07/developing-a-jpa-application-on-jboss-as-7/">posts</a>, we have seen how to develop RESTful application with JBoss AS 7. At the end of the second blog we used a generic REST client tool to execute some RESTful web services. Of course we would rather build a custom UI application as client for our services, so that a user can easily access and manipulate the data. In this blog we build a REST client that is based on the <a href="http://en.wikipedia.org/wiki/Master-detail">master-detail principle</a>.<br />
<span id="more-7207"></span></p>
<h3>REST and Master-Detail</h3>
<p>A RESTful web service, as developed in the previous posts is essentially an editable collection. This makes a Master-Detail design a prime candidate for the User Interface on top of it: The UI will display the entire collection in the master view and a single entry in the collection will be made editable in the detail view.<br />
<a href="http://blog.xebia.com/wp-content/uploads/2011/09/master-detail.png"><img class="alignleft size-medium wp-image-7513" src="http://blog.xebia.com/wp-content/uploads/2011/09/master-detail-300x200.png" alt="" width="300" height="200" /></a><br />
How do we implement this? Well, the web services produce data in the JSON format. A client will have to consume this data and display it in a User Interface. A JavaScript client is a very good choice for this, since JSON is a sort-of &#8220;native&#8221; format for JavaScript. Of course other options are possible, you could develop a client with Adobe Flex or JavaFX, for example. An advantage of using simple HTML and JavaScript would be that there are a lot of applications (web browsers) that understand these languages and can be used to run the REST client.<br />
There are a number of frameworks that can be used to develop a REST client in JavaScript. A popular choice is <a href="http://documentcloud.github.com/backbone/">BackBone.js</a> with <a href="http://mustache.github.com/">Mustache</a>.<br />
For this blog I have chosen to develop the client as a <a href="http://jquery.com/">jQuery</a> plugin. jQuery is a general purpose JavaScript library with a lot of features. We are going to use its templating feature to display the data.</p>
<h3>Using jQuery template for the Master view</h3>
<p>Let&#8217;s first look at the master view. This will be a table with a row for each book, displaying the id and the title.</p>
<table>
<tbody>
<tr>
<td><img class="alignleft size-full wp-image-7518" style="margin-left: -55px; border: 1px solid black;" src="http://blog.xebia.com/wp-content/uploads/2011/09/master-table.png" alt="" width="301" height="128" /></td>
<td><img class="alignleft size-full wp-image-7519" style="margin-left: -12px;" src="http://blog.xebia.com/wp-content/uploads/2011/09/matser-table-html.png" alt="" width="448" height="360" /></td>
</tr>
</tbody>
</table>
<p>What we need for this is a simple jQuery template that displays a single row for each book and an appropriate container in which the rows can be placed.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;script id=&quot;bookRowTemplate&quot; type=&quot;text/x-jquery-tmpl&quot;&gt;
  &lt;tr&gt;
	&lt;td class=&quot;idCol&quot;&gt;&lt;a href=&quot;#&quot; data-id=&quot;${id}&quot; class=&quot;bookSelect&quot;&gt;${id}&lt;/a&gt;&lt;/td&gt;
	&lt;td class=&quot;titleCol&quot;&gt;${title}&lt;/td&gt;
	&lt;td&gt;&lt;a href=&quot;#&quot; data-id=&quot;${id}&quot; class=&quot;bookDelete&quot;&gt;delete&lt;/a&gt;&lt;/td&gt;
  &lt;/tr&gt;
&lt;/script&gt;
</pre>
<p>The jQuery template can be a script tag in the header of the page. It should have the type <span style="font-family: monospace;">text/x-jquery-tmpl</span> and an appropriate id for referencing. Properties of the objects we want to display (in this case the id and title of the book) can be inserted using <span style="font-family: monospace;">${&#8230;}</span> notation.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;table&gt;
	&lt;caption&gt;Books&lt;/caption&gt;
	&lt;thead&gt;
		&lt;tr&gt;
			&lt;th class=&quot;idCol&quot;&gt;Id&lt;/th&gt;
			&lt;th class=&quot;titleCol&quot;&gt;Title&lt;/th&gt;
		&lt;/tr&gt;
	&lt;/thead&gt;
	&lt;tbody id=&quot;booksContainer&quot;&gt;&lt;/tbody&gt;
&lt;/table&gt;
</pre>
<p>The container element is in this case a <span style="font-family: monospace;">tbody</span> with <span style="font-family: monospace;">id=&#8221;booksContainer&#8221;</span>. The pattern in the ids used here will become more clear later.</p>
<h3>Loading the data and filling out the template</h3>
<p>Now how do we download the data and use the template to show it?</p>
<pre class="brush: jscript; title: ; notranslate">
function loadList (options) {
	doAjaxCall('GET', options.url, null, function(data) {
		useTemplate(options.rowTemplate, data, options.rowsContainer);
	});
}

function doAjaxCall(type, url, data, callback) {
	$.ajax({
		type: type,
		url: url,
		dataType: &quot;json&quot;,
		data: data,
		success: callback
	});
}

function useTemplate(template, data, container) {
	if (template) {
		container.empty();
		template.tmpl(data).appendTo(container);
	}
}
</pre>
<p>The loadList function loads the data and displays it in the master view. It uses the doAjaxCall function to start the asynchronous loading. This is merely a wrapper around the standard jQuery <span style="font-family: monospace;">ajax</span> function, but it will be used in many more places. When the ajax call returns successfully, the useTemplate function is used to display the returned data in the template.<br />
The options object that is referenced in some places, is a container for configuration options for the client, that will be discussed later. The relevant configuration options here are:</p>
<pre class="brush: jscript; title: ; notranslate">
var options = {
	url: 'books/',
	rowTemplate: $('#bookRowTemplate'),
	rowsContainer: $('#booksContainer')
};
</pre>
<p>The JSON that is loaded for display is shown below. In this case it is a list of objects, where each object is a book with an id and a title. Since it is a list, the template will be applied to each element and the resulting HTML is concatenated.<br />
<a href="http://blog.xebia.com/wp-content/uploads/2011/09/get-data.png"><img class="aligncenter size-medium wp-image-7541" title="get-data" src="http://blog.xebia.com/wp-content/uploads/2011/09/get-data.png" alt="" width="600" /></a></p>
<h3>Selecting and deleting items from the list</h3>
<p>The template for each row contains two links, one for selecting an item, the other for deleting it. How do these work?</p>
<pre class="brush: jscript; title: ; notranslate">
// opts.selectLinks = $('.bookSelect');
opts.selectLinks.live('click', function (event) {
	var id = $(this).data('id');
	doAjaxCall('GET', url(opts.url, id), null, function(data) {
		useTemplate(opts.entryTemplate, data, opts.entryContainer);
	});
	event.preventDefault();
});

//opts.deleteLinks = $('.bookDelete');
opts.deleteLinks.live('click', function (event) {
	var id = $(this).data('id');
	doAjaxCall('DELETE', url(opts.url, id), null, function(data) {
		doResetAndReload(opts);
	});
	event.preventDefault();
});

function url(url, id) {
	return url + id + '/';
}
</pre>
<p>Handlers for the click events are attached to these links using jQueries <a href="http://api.jquery.com/live/"><span style="font-family: monospace;">live</span></a> function. From the documentation</p>
<blockquote><p>Attach a handler to the event for all elements which match the current selector, now and in the future.</p></blockquote>
<p>In our case, the row template generates class attributes for the links that can be used for attaching the handler. For both operations, we need the id of the book we want to select or delete. For easy access, the template generates a data attribute (<span style="font-family: monospace;">data-id</span>) in the links. In the event handlers, the id is retrieved from the node and used to make another ajax call. For the delete links, a <span style="font-family: monospace;">DELETE</span> method is called and on success the UI is reset and the list reloaded. For the select links we need to display the detail data of the item in an entry form.</p>
<h3>The detail view as entry form</h3>
<p>The entry form should display the data for one item in the list (in our case a book) and it should allow the user to <span style="font-family: monospace;">POST</span> or <span style="font-family: monospace;">PUT</span> the data in the form to a Web Service. The static HTML is fairly simple:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;div id=&quot;bookContainer&quot;&gt;
Book:
&lt;form id=&quot;bookForm&quot;&gt;
	&lt;fieldset id=&quot;bookEntryContainer&quot;&gt;
	&lt;/fieldset&gt;
	&lt;input type=&quot;reset&quot; value=&quot;Cancel&quot; /&gt;
	&lt;input type=&quot;submit&quot; value=&quot;Save&quot; /&gt;
&lt;/form&gt;
&lt;/div&gt;
</pre>
<p>The form has only an id attribute and no action or method. This will be handled by the javascript handler for submitting the form. The submit and cancel buttons are static and standard. The interesting part is the fieldset, that will contain the elements rendered by the template.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;script id=&quot;bookEntryTemplate&quot; type=&quot;text/x-jquery-tmpl&quot;&gt;
	&lt;p&gt;Id: ${id}&lt;/p&gt;
	{{if id}}
	&lt;input id=&quot;idField&quot; name=&quot;id&quot; type=&quot;hidden&quot; value=&quot;${id}&quot;/&gt;
	{{/if}}
	&lt;label for=&quot;titleFld&quot;&gt;Title:&lt;/label&gt;
	&lt;input id=&quot;titleFld&quot; name=&quot;title&quot; value=&quot;${title}&quot;/&gt;
&lt;/script&gt;
</pre>
<p>In this template there is a little logic to handle the cases for new and existing books. An existing book can be recognized by its id property. If the id property is filled, it should be set and send to the web service by adding the hidden input field.<br />
The JavaScript handle the form events is a little bit more complicated.</p>
<pre class="brush: jscript; title: ; notranslate">
opts.entryForm.submit(function (event) {
	var form = $(this);
	var data = form.serialize();
	var id = $('#'+opts.entryIdField).val();
	if (id) {
		doAjaxCall('PUT', url(opts.url, id), data, function(data) {
			doResetAndReload(opts);
		});
	} else {
		doAjaxCall('POST', opts.url, data, function(data) {
			doResetAndReload(opts);
		});
	}
	event.preventDefault();
});

opts.entryForm.bind('reset', function (event) {
	onSelect(opts, null);
	event.preventDefault();
});
</pre>
<p>When submitting the form, we want to send the contents as form data to through an ajax call. If the id is not set, a <span style="font-family: monospace;">POST</span> method is called to create a new instance. If the id is set, a <span style="font-family: monospace;">PUT</span> method should be called with the id appended to the URL. In both cases we want to reset the UI and reload the list on a successful return.</p>
<h3>Icing on the cake: Expanding options</h3>
<p>This is basically all the code for this master-detail based REST client with jQuery templates. With this code you can do simple CRUD operations on simple books, as shown in the screenshots below.<br />
<a href="http://blog.xebia.com/wp-content/uploads/2011/09/scenario1.png"><img src="http://blog.xebia.com/wp-content/uploads/2011/09/scenario1-240x300.png" alt="" title="Selected the Third book" width="240" height="300" class="aligncenter size-medium wp-image-7563" style="margin-left: -30px"/></a><a href="http://blog.xebia.com/wp-content/uploads/2011/09/scenario2.png"><img src="http://blog.xebia.com/wp-content/uploads/2011/09/scenario2-240x300.png" alt="" title="Updated the third book" width="240" height="300" class="aligncenter size-medium wp-image-7564" /></a><a href="http://blog.xebia.com/wp-content/uploads/2011/09/scenario3.png"><img src="http://blog.xebia.com/wp-content/uploads/2011/09/scenario3-240x300.png" alt="" title="Deleted the Second book" width="240" height="300" class="aligncenter size-medium wp-image-7565" style="margin-right: -30px"/></a></p>
<p>Now how about those options that you kept on hearing about? I designed the client to be able to use multiple REST clients for related collections on the same page. Therefore I wanted some mechanism that would allow me to do</p>
<pre class="brush: jscript; title: ; notranslate">
new RestClient({name:'book'});
new RestClient({name:'author'});
</pre>
<p>and the client would figure out which templates, which containers and which forms to use for display and entry purposes. This is accomplished by using configurations that are expanded to include the value for other options.</p>
<pre class="brush: jscript; title: ; notranslate">
RestClient = function (options) {
	var opts = $.extend({}, RestClient.defaults, options);
	expand(opts);
	...
};
RestClient.defaults = {
	plural: '{name}s',

	baseUrl: 'services',
	url: '{baseUrl}/{plural}/',

	rowTemplate: '#{name}RowTemplate',
	rowsContainer: '#{plural}Container',

	entryTemplate: '#{name}EntryTemplate',
	entryContainer: '#{name}EntryContainer',
	entryForm: '#{name}Form',
	entryIdField: 'idField',

	selectLinks: '.{name}Select',
	deleteLinks: '.{name}Delete',

	onSelect: $.noop,
	onReload: $.noop
};
</pre>
<p>The options passed into the constructor extend the default options, which allows for customizing the options anyway you would want. After the extension is applied, the values are expanded, basically replacing every occurrence of <span style="font-family: monospace;">{&#8230;}</span> by the option value referenced by that name.</p>
<pre class="brush: jscript; highlight: [10,11,12,13,14,15,16,17,18]; title: ; notranslate">
function expand(options) {
	for (var field in options) {
		var val = options[field];
		if ($.type(val) == 'string') {
			while (val.match(/{([^{}]*)}/)) {
				val = val.replace(/{([^{}]*)}/, function (key, group) {
					return options[group];
				});
			}
			if (val.charAt(0) == '#' || val.charAt(0) == '.') {
				var obj = $(val);
				if (val.charAt(0) == '#') {
					if (obj.length == 0) {
						obj = undefined;
					}
				}
				val = obj;
			}
			options[field] = val;
		}
	}
}
</pre>
<p>The highlighted lines in this code fragment resolve any CSS selectors through jQuery after expanding them.<br />
As an example (and a short preview) the screenshot below shows a page with two Master-Detail implementations, one for books and one for authors, both implemented using this plugin.<br />
<a href="http://blog.xebia.com/wp-content/uploads/2011/09/Screen-shot-2011-09-15-at-4.47.20-PM.png"><img src="http://blog.xebia.com/wp-content/uploads/2011/09/Screen-shot-2011-09-15-at-4.47.20-PM-280x300.png" alt="" title="Master-Detail for Books and Authors" width="280" height="300" class="aligncenter size-medium wp-image-7577" /></a></p>
<h3>Conclusion</h3>
<p>Writing a JavaScript client for RESTful web services is very simple with jQuery and jQuery template. The source code for this blog can be downloaded here:<br />
<a href='http://blog.xebia.com/wp-content/uploads/2011/09/books.html'>books.html</a> <a href='http://blog.xebia.com/wp-content/uploads/2011/09/jquery.rest-client.js'>jquery.rest-client.js</a> <a href='http://blog.xebia.com/wp-content/uploads/2011/09/books.css'>books.css</a><br />
Since the backend is not deployed, the page is not functional <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2011/09/15/master-detail-implementation-for-restful-services-with-jquery/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2011%2F09%2F15%2Fmaster-detail-implementation-for-restful-services-with-jquery%2F&amp;title=Master-detail%20implementation%20for%20RESTful%20services%20with%20JQuery" id="wpa2a_4"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2011/09/15/master-detail-implementation-for-restful-services-with-jquery/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Developing a JPA application on JBoss AS 7</title>
		<link>http://blog.xebia.com/2011/07/19/developing-a-jpa-application-on-jboss-as-7/</link>
		<comments>http://blog.xebia.com/2011/07/19/developing-a-jpa-application-on-jboss-as-7/#comments</comments>
		<pubDate>Tue, 19 Jul 2011 07:00:23 +0000</pubDate>
		<dc:creator>Maarten Winkels</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[JBoss]]></category>
		<category><![CDATA[JPA]]></category>

	<!-- AutoMeta Start -->
	<category>postgres</category>
	<category>postgresql</category>
	<category>jdbc4</category>
	<category>bookrepository</category>
	<category>book_seq</category>
	<category>pathparam</category>
	<category>driver</category>
	<category>arquillian</category>
	<category>postgres</category>
	<category>postgresql</category>
	<category>jdbc4</category>
	<category>bookrepository</category>
	<category>book_seq</category>
	<category>pathparam</category>
	<category>driver</category>
	<category>arquillian</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=7138</guid>
		<description><![CDATA[In my previous post we setup a Maven/Eclipse project for developing RESTful web applications on JBoss AS 7. A RESTful web service that is not using a database is some what of an oddity. Therefor in this blog we&#8217;ll extend the project with JPA. Configuration: Adding a JBoss Module I want to use Postgres as [...]]]></description>
			<content:encoded><![CDATA[<p><a href="https://docs.jboss.org/author/display/AS7/Documentation"><img src="http://blog.xebia.com/wp-content/uploads/2011/07/as7_logo.png" alt="" title="JBoss AS 7" style="float:right; height:100px" /></a>In my <a href="http://blog.xebia.com/2011/07/developing-restful-applications-on-jboss-as-7/">previous post</a> we setup a Maven/Eclipse project for developing RESTful web applications on <a href="http://www.jboss.org/jbossas/downloads">JBoss AS 7</a>. A RESTful web service that is not using a database is some what of an oddity. Therefor in this blog we&#8217;ll extend the project with JPA.</p>
<p><span id="more-7138"></span></p>
<h3>Configuration: Adding a JBoss Module</h3>
<p>I want to use <a href="http://www.postgresql.org/">Postgres</a> as the underlying database. To install the required JDBC driver for Postgres in the JBoss AS 7 container, we need to add a module. As I mentioned in the previous post, the module structure of JBoss is reflected on the file system.<br />
<a href="http://blog.xebia.com/wp-content/uploads/2011/07/PostgresModule.png"><img src="http://blog.xebia.com/wp-content/uploads/2011/07/PostgresModule-300x126.png" alt="" title="PostgresModule" width="300" height="126" class="aligncenter size-medium wp-image-7142" /></a><br />
The files in the &#8221;main&#8221; directory that constitute the module are the folloing:</p>
<ul>
<li><b>module.xml</b> describes the module. The content follows below.</li>
<li><b>postgresql-9.0-801.jdbc4.jar</b> is the postgres JDBC4 driver.</li>
<li><b>postgresql-9.0-801.jdbc4.jar.index</b> is an index file generated by JBoss Annotation Indexer when the modules are scanned.</li>
</ul>
<p>So in order to add a module to the JBoss container, we need to write an XML file:</p>
<pre class="brush: xml; title: module.xml; notranslate">
&lt;module xmlns=&quot;urn:jboss:module:1.0&quot; name=&quot;org.postgres&quot;&gt;
  &lt;resources&gt;
    &lt;resource-root path=&quot;postgresql-9.0-801.jdbc4.jar&quot;/&gt;
  &lt;/resources&gt;

   &lt;dependencies&gt;
     &lt;module name=&quot;javax.api&quot;/&gt;
     &lt;module name=&quot;javax.transaction.api&quot;/&gt;
   &lt;/dependencies&gt;
&lt;/module&gt;
</pre>
<p>Now we also need to enlist the datasource in the standalone.xml: the main configuration for JBoss. You&#8217;ll find it in the &#8221;standalone/configuration&#8221; subdirectory of the JBoss installation. The file already has a datasource and driver for h2. So we add a new node:</p>
<pre class="brush: xml; highlight: [9,10,11,12,13]; title: standalone.xml; notranslate">
&lt;?xml version='1.0' encoding='UTF-8'?&gt;
&lt;server name=&quot;brandhout.local&quot; xmlns=&quot;urn:jboss:domain:1.0&quot;&gt;
...
            &lt;datasources&gt;
                &lt;datasource&gt;
...
                &lt;/datasource&gt;
                &lt;drivers&gt;
                    &lt;driver name=&quot;postgres&quot; module=&quot;org.postgres&quot;&gt;
                        &lt;xa-datasource-class&gt;
                            org.postgresql.xa.PGXADataSource
                        &lt;/xa-datasource-class&gt;
                    &lt;/driver&gt;
                    &lt;driver name=&quot;h2&quot; module=&quot;com.h2database.h2&quot;&gt;
                        &lt;xa-datasource-class&gt;
                            org.h2.jdbcx.JdbcDataSource
                        &lt;/xa-datasource-class&gt;
                    &lt;/driver&gt;
                &lt;/drivers&gt;
            &lt;/datasources&gt;
...
&lt;/server&gt;
</pre>
<p>Now, after restarting the server, we can finish the configuration using the admin console.<br />
<a href="http://blog.xebia.com/wp-content/uploads/2011/07/ConfigureDataSource.png"><img src="http://blog.xebia.com/wp-content/uploads/2011/07/ConfigureDataSource-300x209.png" alt="" title="ConfigureDataSource" width="300" height="209" class="aligncenter size-medium wp-image-7152" /></a><br />
The &#8221;New Datasource&#8221; button will open up a dialog that will guide you through a few simple steps to configure the datasource.<br />
The changes will be persisted in the standalone.xml, which will now contain a fragment like this:</p>
<pre class="brush: xml; title: standalone.xml; notranslate">
..
                &lt;datasource jndi-name=&quot;LibraryDS&quot; pool-name=&quot;LibraryDS_Pool&quot; enabled=&quot;true&quot; jta=&quot;true&quot; use-java-context=&quot;true&quot; use-ccm=&quot;true&quot;&gt;
                    &lt;connection-url&gt;
                        jdbc:postgresql://localhost:5432/library
                    &lt;/connection-url&gt;
                    &lt;driver&gt;
                        postgres
                    &lt;/driver&gt;
                    &lt;security&gt;
                        &lt;user-name&gt;
                            library
                        &lt;/user-name&gt;
                        &lt;password&gt;
                            library
                        &lt;/password&gt;
                    &lt;/security&gt;
                &lt;/datasource&gt;
...
</pre>
<h3>Reading from the database</h3>
<p>Now we need to configure our application to read from the database. To configure the database as a persistence context in JPA, we add a persistence.xml to our project.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;persistence xmlns=&quot;http://java.sun.com/xml/ns/persistence&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd&quot;
	version=&quot;1.0&quot;&gt;

	&lt;persistence-unit name=&quot;library&quot; transaction-type=&quot;JTA&quot;&gt;
		&lt;provider&gt;org.hibernate.ejb.HibernatePersistence&lt;/provider&gt;
		&lt;jta-data-source&gt;java:/LibraryDS&lt;/jta-data-source&gt;
		&lt;properties&gt;
			&lt;property name=&quot;hibernate.hbm2ddl.auto&quot; value=&quot;create-drop&quot; /&gt;
		&lt;/properties&gt;
	&lt;/persistence-unit&gt;

&lt;/persistence&gt;
</pre>
<p>The java code we have to write is quite trivial JPA code mixed in with some JAX-RS annotation. For completeness they are included here below (collapsed).</p>
<pre class="brush: java; collapse: true; light: false; title: com/xebia/library/model/Book.java; toolbar: true; notranslate">
package com.xebia.library.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.ws.rs.FormParam;

@Entity
@SequenceGenerator(name=&quot;BOOK_SEQ&quot;, sequenceName=&quot;BOOK_SEQ&quot;)
public class Book {

	@Id
	@GeneratedValue(strategy=GenerationType.SEQUENCE, generator=&quot;BOOK_SEQ&quot;)
	@FormParam(&quot;id&quot;)
	private Long id;

	@FormParam(&quot;title&quot;)
	private String title;

	public Long getId() {
		return id;
	}

	public String getTitle() {
		return title;
	}
}
</pre>
<pre class="brush: java; collapse: true; light: false; title: com/xebia/library/BookRepository.java; toolbar: true; notranslate">
package com.xebia.library;

import static javax.ws.rs.core.MediaType.APPLICATION_JSON;

import java.util.List;

import javax.ejb.Local;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import org.jboss.resteasy.annotations.Form;

import com.xebia.library.model.Book;

@Local
@Path(&quot;books&quot;)
@Produces(APPLICATION_JSON)
public interface BookRepository {
	@GET
	@Path(&quot;/&quot;)
	List&lt;Book&gt; all();

	@POST
	@Path(&quot;/&quot;)
	Book create(@Form Book entity);

	@GET
	@Path(&quot;/{id}/&quot;)
	Book getById(@PathParam(&quot;id&quot;) long id);

	@PUT
	@Path(&quot;/{id}/&quot;)
	Book update(@Form Book entity);

	@DELETE
	@Path(&quot;/{id}/&quot;)
	void remove(@PathParam(&quot;id&quot;) long id);
}
</pre>
<pre class="brush: java; collapse: true; light: false; title: com/xebia/library/impl/BookRepositoryBean.java; toolbar: true; notranslate">
package com.xebia.library.impl;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import com.xebia.library.BookRepository;
import com.xebia.library.model.Book;

@Stateless
public class BookRepositoryBean implements BookRepository {

	@PersistenceContext
	private EntityManager em;

	@Override
	public List&lt;Book&gt; all() {
		CriteriaBuilder builder = em.getCriteriaBuilder();
		CriteriaQuery&lt;Book&gt; query = builder.createQuery(Book.class);
		Root&lt;Book&gt; root = query.from(Book.class);
		query.orderBy(builder.asc(root.get(&quot;id&quot;)));
		return em.createQuery(query).getResultList();
	}

	@Override
	public Book create(Book book) {
		em.persist(book);
		return book;
	}

	@Override
	public Book byId(long id) {
		return em.find(Book.class, id);
	}

	@Override
	public Book update(long id, Book book) {
		return em.merge(book);
	}

	@Override
	public void delete(long id) {
		em.remove(byId(id));
	}

}
</pre>
<p>A few things to notice:</p>
<ul>
<li>The JPA entity is also used as a &#8221;backing&#8221; object for Form posts. The @FormParam annotation is used to parameters posted to the fields of the object.</li>
<li>The Repository is now also used as a local interface for the stateless bean.</li>
</ul>
<p>After deploying the application to the server, we can test it using <a href="http://code.google.com/p/rest-client/">this simple tool</a>.<br />
<a href="http://blog.xebia.com/wp-content/uploads/2011/07/RestClient1.png"><img src="http://blog.xebia.com/wp-content/uploads/2011/07/RestClient1-300x263.png" alt="" title="RestClient" width="300" height="263" class="aligncenter size-medium wp-image-7177" /></a></p>
<h2>Conclusion</h2>
<p>With just a few classes we were able to deploy a RESTful web service that enables users to maintain a (rudimentary) book list. The WAR that we build is really tiny: It only contains a few classes. The application relies on JEE specifications that are implemented in the JBoss container. A few remarks about this:</p>
<ol>
<li>Developing a JEE application becomes much simpler and more fun! It feels almost like RAD web development alla Grails.</li>
<li>Testing an application like this is non-trivial: Much of the functionality is provided by the container. With a &#8216;thicker&#8217; maven project with Hibernate and Spring/Seam as dependencies, we could mimic (parts of) the deployed application in an in-build testing environment. How do we do this now? One possible answer is to use <a href="http://www.jboss.org/arquillian">Arquillian</a>. A future blog will have to cover that&#8230;</li>
</ol>
<p>Of course the application we have now is far from finished. To start with, it has no user interface&#8230;</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2011/07/19/developing-a-jpa-application-on-jboss-as-7/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2011%2F07%2F19%2Fdeveloping-a-jpa-application-on-jboss-as-7%2F&amp;title=Developing%20a%20JPA%20application%20on%20JBoss%20AS%207" id="wpa2a_6"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2011/07/19/developing-a-jpa-application-on-jboss-as-7/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Developing RESTful applications on JBoss AS 7</title>
		<link>http://blog.xebia.com/2011/07/12/developing-restful-applications-on-jboss-as-7/</link>
		<comments>http://blog.xebia.com/2011/07/12/developing-restful-applications-on-jboss-as-7/#comments</comments>
		<pubDate>Tue, 12 Jul 2011 07:00:25 +0000</pubDate>
		<dc:creator>Maarten Winkels</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[JBoss]]></category>
		<category><![CDATA[jboss tools]]></category>
		<category><![CDATA[jee 6]]></category>
		<category><![CDATA[rest]]></category>

	<!-- AutoMeta Start -->
	<category>bookrepository</category>
	<category>applicationpath</category>
	<category>restful</category>
	<category>modules</category>
	<category>modules</category>
	<category>resteasy</category>
	<category>jboss</category>
	<category>admin</category>
	<category>bookrepository</category>
	<category>applicationpath</category>
	<category>restful</category>
	<category>modules</category>
	<category>modules</category>
	<category>resteasy</category>
	<category>jboss</category>
	<category>admin</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=6767</guid>
		<description><![CDATA[JBoss AS 7 CR1 has been released recently. On the previous release it was pretty easy to develop RESTful applications with the build in JAX-RS support based on RESTeasy. In this blog I&#8217;ll look at how well the new version of JBoss keeps up with the rest of the field. Changes: JBoss Modules JBoss AS [...]]]></description>
			<content:encoded><![CDATA[<p><a href="https://docs.jboss.org/author/display/AS7/Documentation"><img src="http://blog.xebia.com/wp-content/uploads/2011/07/as7_logo.png" alt="" title="JBoss AS 7" style="float:right; height:100px" /></a><a href="http://www.jboss.org/jbossas/downloads">JBoss AS 7 CR1</a> has been released recently. On the previous release it was pretty easy to develop RESTful applications with the build in JAX-RS support based on RESTeasy. In this blog I&#8217;ll look at how well the new version of JBoss keeps up with the rest of the field.</p>
<p><span id="more-6767"></span></p>
<h3>Changes: JBoss Modules</h3>
<p>JBoss AS 7 is quite a different beast from its predecessors. The most striking difference is the usage of <a href="https://docs.jboss.org/author/display/MODULES/Home">JBoss modules</a>, which is a modular class loading system, comparable to <a href="http://mreinhold.org/blog/jigsaw">Jigsaw</a>, THE modular system for Java that will (one day) (probably) reach the JVM. Till that day however, JBoss modules can be used.</p>
<p>After downloading and unzipping the JBoss AS 7 CR1 release, you&#8217;ll find all the modules in the &#8221;modules&#8221; subdirectory, grouped in a structure that somewhat resembles a maven repository: you&#8217;ll for example find directories for &#8221;org&#8221;, &#8221;javax&#8221; and &#8221;net&#8221;, similar to the directory structure of group-ids and artifact-ids in a Maven2 repository layout. At some level, however, there will be a &#8221;main&#8221; folder and that&#8217;s where the implementation details of the module are kept: a small XML file describing the module and some jar files that constitute the modules content. A very useful side effect of this is that finding out which versions of which jars the AS is using is rather simple: The jar files in the module are usually the maven artifacts and thus contain the version number in their name. See for example the javax.activation module below.<br />
<a href="http://blog.xebia.com/wp-content/uploads/2011/07/JbossModules.png"><img src="http://blog.xebia.com/wp-content/uploads/2011/07/JbossModules-300x114.png" alt="" title="JbossModules" width="300" height="114" class="aligncenter size-medium wp-image-7185" /></a></p>
<p>Another consequence of this change is that the usual JBoss structure with a &#8221;server&#8221; directory with several profiles, like &#8221;default&#8221;, &#8221;web&#8221; and &#8221;minimal&#8221; no longer exists. The main structure now has a &#8221;standalone&#8221; directory for running a simple server, and a &#8221;domain&#8221; directory for running a cluster.</p>
<h3>Installation</h3>
<p>Installation is as always straight forward. A development environment however is not ready for use without good integration between the IDE and the application server on the local system. IDE of choice is Eclipse, because of the nice JBoss Tools plugin suite. Following <a href="https://docs.jboss.org/author/display/AS7/Starting+JBoss+AS+from+Eclipse+with+JBoss+Tools">these instructions</a> is already a large part of the installation.</p>
<p>To make things really easy, we include <a href="http://eclipse.org/m2e/">Maven integration for Eclipse</a> with WTP from Sonatype into the mix. Especially finding the right version of the Maven integration for WTP was difficult. I finally found a copy that worked with the rest of the setup at this <a href="https://repository.sonatype.org/content/sites/forge-sites/m2eclipse-wtp/0.13.0/S/0.13.0.20110623-0455/">update site</a>.</p>
<p>Starting the server can now be done from the Eclipse servers window. Browsing to the default port shows a nice welcome window and going to the admin console shows a simple but useful administrative interface.<br />
<a href="http://blog.xebia.com/wp-content/uploads/2011/07/welcome.png"><img src="http://blog.xebia.com/wp-content/uploads/2011/07/welcome-300x235.png" alt="" title="welcome" width="300" height="235" class="alignleft size-medium wp-image-7108" /></a><a href="http://blog.xebia.com/wp-content/uploads/2011/07/admin.png"><img src="http://blog.xebia.com/wp-content/uploads/2011/07/admin-300x235.png" alt="" title="admin" width="300" height="235" class="alignleft size-medium wp-image-7107" /></a><br />
Two small problems with the setup so far:<br />
1. Eclipse doesn&#8217;t seem to detect the startup of the server. Which is kind of annoying, because Eclipse now wont compile anything since it is waiting for the process to end.<br />
<a href="http://blog.xebia.com/wp-content/uploads/2011/07/NotStarted.png"><img src="http://blog.xebia.com/wp-content/uploads/2011/07/NotStarted-300x251.png" alt="" title="NotStarted" width="300" height="251" class="aligncenter size-medium wp-image-7112" /></a><br />
This can be worked around by setting the Startup Poller to &#8221;Web Port Poller&#8221; in the Server overview screen of the JBoss 7 AS server.<br />
<img src="http://blog.xebia.com/wp-content/uploads/2011/07/StartUpFix.png" alt="" title="StartUpFix" width="572" height="92" class="aligncenter size-full wp-image-7113" /><br />
2. Eclipse is not able to stop JBoss. At least not from the server view.<br />
<a href="http://blog.xebia.com/wp-content/uploads/2011/07/CannotStop.png"><img src="http://blog.xebia.com/wp-content/uploads/2011/07/CannotStop-300x164.png" alt="" title="CannotStop" width="300" height="164" class="aligncenter size-medium wp-image-7111" /></a><br />
JBoss can still be stopped from the Console view, but that means restarting the server always takes at least 4 mouse clicks: (1) go to console (2) stop (3) go to servers (4) restart, which is kind of annoying.</p>
<p>Anyway, living with small annoyances is second nature for everybody in IT industry I suppose, so why would a simple JEE application developer be any different <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<h3>Starting up the project</h3>
<p>Now that everything is set up, we can continue to the more interesting part, the project and the Java code. With the help of M2Eclipse we create a maven project with the following pom:</p>
<pre class="brush: xml; highlight: [41,42,43,44,45,46,47]; title: ; notranslate">
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
	&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
	&lt;groupId&gt;com.xebia.library&lt;/groupId&gt;
	&lt;artifactId&gt;library&lt;/artifactId&gt;
	&lt;version&gt;0.9-SNAPSHOT&lt;/version&gt;
	&lt;packaging&gt;war&lt;/packaging&gt;
	&lt;repositories&gt;
		&lt;repository&gt;
			&lt;id&gt;jboss&lt;/id&gt;
			&lt;url&gt;https://repository.jboss.org/nexus/content/groups/public-jboss/&lt;/url&gt;
		&lt;/repository&gt;
	&lt;/repositories&gt;
	&lt;build&gt;
		&lt;plugins&gt;
			&lt;plugin&gt;
				&lt;artifactId&gt;maven-resources-plugin&lt;/artifactId&gt;
				&lt;version&gt;2.4.3&lt;/version&gt;
				&lt;configuration&gt;
					&lt;encoding&gt;UTF-8&lt;/encoding&gt;
				&lt;/configuration&gt;
			&lt;/plugin&gt;
			&lt;plugin&gt;
				&lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
				&lt;version&gt;2.3.2&lt;/version&gt;
				&lt;configuration&gt;
					&lt;source&gt;1.6&lt;/source&gt;
					&lt;target&gt;1.6&lt;/target&gt;
				&lt;/configuration&gt;
			&lt;/plugin&gt;
			&lt;plugin&gt;
				&lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt;
				&lt;version&gt;2.1.1&lt;/version&gt;
				&lt;configuration&gt;
					&lt;failOnMissingWebXml&gt;false&lt;/failOnMissingWebXml&gt;
				&lt;/configuration&gt;
			&lt;/plugin&gt;
		&lt;/plugins&gt;
	&lt;/build&gt;
	&lt;dependencies&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.jboss.spec&lt;/groupId&gt;
			&lt;artifactId&gt;jboss-javaee-6.0&lt;/artifactId&gt;
			&lt;version&gt;2.0.0.CR1&lt;/version&gt;
			&lt;type&gt;pom&lt;/type&gt;
			&lt;scope&gt;provided&lt;/scope&gt;
		&lt;/dependency&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.jboss.resteasy&lt;/groupId&gt;
			&lt;artifactId&gt;resteasy-jaxrs&lt;/artifactId&gt;
			&lt;version&gt;2.2.1.GA&lt;/version&gt;
			&lt;scope&gt;provided&lt;/scope&gt;
		&lt;/dependency&gt;
	&lt;/dependencies&gt;
&lt;/project&gt;
</pre>
<p>This pom will configure the maven project and the Eclipse-WTP project correctly for deployment on JBoss. The highlighted lines show the dependency on a pom with the Aggregated Java EE 6.0 APIs that JBoss provides. This pom is supposed to be used to import the right version numbers of all the Java EE APIs into your own pom. Since I am lazy, I&#8217;ll just depend on this pom, so all the APIs are already available in my project without having to specify them separately.</p>
<p>Now we have a well configured Maven Web project in Eclipse. The layout will look like the image below.<br />
<a href="http://blog.xebia.com/wp-content/uploads/2011/07/JavaWebProject.png"><img src="http://blog.xebia.com/wp-content/uploads/2011/07/JavaWebProject-150x150.png" alt="" title="JavaWebProject" width="150" height="150" class="aligncenter size-thumbnail wp-image-7129" /></a></p>
<p>And now for some Java code, how do we configure RESTeasy framework?</p>
<pre class="brush: java; title: com/xebia/library/LibraryApplication.java; notranslate">
package com.xebia.library;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath(&quot;services&quot;)
public class LibraryApplication extends Application {

}
</pre>
<p>That&#8217;s it! From the class RESTeasy will be configured and the RESTful web services will be available at &#8221;/services&#8221; in the context of the project.</p>
<p>Let&#8217;s add a simple web service.</p>
<pre class="brush: java; title: com/xebia/library/BookRepository.java; notranslate">
package com.xebia.library;

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.xebia.library.model.Book;

@Path(&quot;books&quot;)
public interface BookRepository {

	@GET
	@Path(&quot;/&quot;)
	@Produces(MediaType.APPLICATION_JSON)
	List&lt;Book&gt; all();
}
</pre>
<p>This interface defines the RESTful web service by means of the JAX-RS annotations. Adding an interface is useful, but not necessary.</p>
<pre class="brush: java; title: com/xebia/library/impl/BookRepositoryBean.java; notranslate">
package com.xebia.library.impl;

import java.util.Collections;
import java.util.List;

import com.xebia.library.BookRepository;
import com.xebia.library.model.Book;

public class BookRepositoryBean implements BookRepository {

	@Override
	public List&lt;Book&gt; all() {
		return Collections.singletonList(new Book(&quot;My Title&quot;));
	}

}
</pre>
<p>The implementation of the web service is very simple (for now) and it uses a very simple POJO as return value.</p>
<pre class="brush: java; title: com/xebia/library/model/Book.java; notranslate">
package com.xebia.library.model;

public class Book {

	private String title;

	public Book() {
	}

	public Book(String title) {
		this.title = title;
	}

	public String getTitle() {
		return title;
	}
}
</pre>
<p>With these simple files, we have all we need to get a RESTful web service running on JBoss AS 7. Pointing the browser to the correct URL, we get a JSON string as shown below.<br />
<a href="http://blog.xebia.com/wp-content/uploads/2011/07/WebServiceResult.png"><img src="http://blog.xebia.com/wp-content/uploads/2011/07/WebServiceResult-300x172.png" alt="" title="WebServiceResult" width="300" height="172" class="aligncenter size-medium wp-image-7133" /></a><br />
The URL is built up from a few parts:</p>
<ol>
<li><b>http://localhost:8080</b> The JBoss web server</li>
<li><b>library</b> The application context</li>
<li><b>services</b> The path configured for the JAX-RS application in the @ApplicationPath annotation</li>
<li><b>books</b> The path for the BookRepository resource as given in the @Path annotation</li>
</ol>
<p>JBoss AS 7 comes with <a href="http://www.jboss.org/resteasy">RESTeasy</a> (an implementation of JAX-RS) and <a href="http://jackson.codehaus.org/">Jackson</a> (a Java-JSON serializarion framework) configured and that is how the final result is obtained. This makes JBoss AS 7 an ideal platform for developing RESTful applications: it works out-of-the-box and is build on well known open source projects, making it easy to adapt the container to specific requirements in you application.</p>
<h2>Conclusion</h2>
<p>In this blog we have set up a development environment for JBoss AS 7 using Maven, Eclipse and WTP and we deployed a very simple RESTful application. The setup works pretty well.<br />
Keep an eye out for new blogs, in which I&#8217;ll improve on the current project to show more aspects of JBoss 7 and RESTful applications.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2011/07/12/developing-restful-applications-on-jboss-as-7/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2011%2F07%2F12%2Fdeveloping-restful-applications-on-jboss-as-7%2F&amp;title=Developing%20RESTful%20applications%20on%20JBoss%20AS%207" id="wpa2a_8"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2011/07/12/developing-restful-applications-on-jboss-as-7/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Writing and testing data structures and algorithms in JavaScript</title>
		<link>http://blog.xebia.com/2011/06/23/writing-and-testing-data-structures-and-algorithms-in-javascript/</link>
		<comments>http://blog.xebia.com/2011/06/23/writing-and-testing-data-structures-and-algorithms-in-javascript/#comments</comments>
		<pubDate>Thu, 23 Jun 2011 17:07:07 +0000</pubDate>
		<dc:creator>Maarten Winkels</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[js_cols]]></category>
		<category><![CDATA[YUI]]></category>

	<!-- AutoMeta Start -->
	<category>tagcounter</category>
	<category>tagcounts</category>
	<category>js_cols</category>
	<category>assertsame</category>
	<category>areequal</category>
	<category>linkedhashmap</category>
	<category>tags</category>
	<category>javascript</category>
	<category>tagcounter</category>
	<category>tagcounts</category>
	<category>js_cols</category>
	<category>assertsame</category>
	<category>areequal</category>
	<category>linkedhashmap</category>
	<category>tags</category>
	<category>javascript</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=6969</guid>
		<description><![CDATA[Tonight in one of our knowledge exchange sessions, one of my colleagues challenged us to writing a TagCloud in JavaScript. He had prepared a nice setup with a server producing twitter hashtags over a WebSocket to the browser and using Processing.js to produce a graphical representation of the tags zooming by on twitter. Since he [...]]]></description>
			<content:encoded><![CDATA[<p>Tonight in one of our knowledge exchange sessions, one of my colleagues challenged us to writing a TagCloud in JavaScript. He had prepared a nice setup with a server producing twitter hashtags over a WebSocket to the browser and using Processing.js to produce a graphical representation of the tags zooming by on twitter. Since he had already done all the heavy lifting in integrating all these fancy new frameworks, what was left to do, you might ask. Well, we still needed to implement the algorithm to count the number of tags on the continuous stream, sorting this list on the bases of the counts and making sure the system wouldn&#8217;t run out of memory by removing less used tags in some smart way. His point to all of this was, that although JavaScript is being prophesized in some circles as the new-old-new language of the future, writing and testing a non-trivial algorithm in it is a big challenge.<br />
<span id="more-6969"></span><br />
In the remainder of the hour, we tried in several pairs to implement the missing algorithm and it has to be said that we all failed miserably. It has to be said that none of us were JavaScript experts, but I (for one) felt (in the beginning&#8230;) that I should have enough experience in IT in general and a little in JavaScript to make this work. But alas&#8230;</p>
<p>Driving back home, I decided not to give in so easily and to try and use some decent frameworks to overcome this challenge.</p>
<h3>JavaScript testing: <a href="http://developer.yahoo.com/yui/3/">YUI</a></h3>
<p>I turned to finding a testing framework first. Sure enough, most javascript testing frameworks focus on fancy UI stuff like asynchronous testing, integration testing or automated multi-browser testing. I was looking for none of that, but a simple xUnit like framework, that I could run in a browser to test the functionality of a number of JavaScript classes. After a few minutes I found <a href="http://developer.yahoo.com/yui/3/">YUI</a> which seemed to fit the bill. Setting up was easy enough:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
&lt;title&gt;Testing TagCounter with YUI&lt;/title&gt;
&lt;/head&gt;
  &lt;body class=&quot;yui-skin-sam&quot;&gt;
    &lt;div id=&quot;yui-main&quot;&gt;&lt;div id=&quot;testReport&quot;&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;http://yui.yahooapis.com/3.0.0/build/yui/yui-min.js&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;js_cols/base.js&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;TagCounter.js&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;TagCounter_Test.js&quot;&gt;&lt;/script&gt;
  &lt;/body&gt;
 &lt;/html&gt;
</pre>
<p>This static html file is all that is neede to run my tests. The tests themselves are written in the TagCounter_Test.js file:</p>
<pre class="brush: jscript; title: ; notranslate">
/**
 * Unit Tests for TagCounter
 */
YUI({
  combine: true,
  timeout: 10000
}).use(&quot;node&quot;, &quot;console&quot;, &quot;test&quot;, function (Y) {
  var assert = Y.Assert;

  var TagCounterTestCase = new Y.Test.Case({
    // test case name - if not provided, one is generated
    name: &quot;TagCounter Tests&quot;,

    &quot;test should increment count&quot;: function () {
      var tc = new TagCounter();
      tc.add(&quot;my-tag&quot;);
      assert.areEqual(1, tc.map().get(&quot;my-tag&quot;));
      tc.add(&quot;my-tag&quot;);
      assert.areEqual(2, tc.map().get(&quot;my-tag&quot;));
    }
  });

  //create the console
  var r = new Y.Console({
    newestOnTop : false,
    style: 'block'
  });

  r.render(&quot;#testReport&quot;);
  Y.Test.Runner.add(TagCounterTestCase);
  Y.Test.Runner.run();
});</pre>
<p>Opening the HTML file in FireFox shows the picture below.<br />
<img src="http://blog.xebia.com/wp-content/uploads/2011/06/Screen-shot-2011-06-22-at-2.46.10-AM.png" alt="" title="Screen shot 2011-06-22 at 2.46.10 AM" width="396" height="537" class="alignright size-full wp-image-6974" /><br />
It seems like I&#8217;m ready to implement the TagCounter TDD style!</p>
<h3>Implementation: <a href="http://code.google.com/p/jscols/">js_cols</a></h3>
<p>To make this simple test pass, all I need is a simple HashMap with some basic features, like contains, get and remove, but&#8230; this is not java! After some googling, I found <a href="http://code.google.com/p/jscols/">js_cols</a>, a neat JavaScript collections framework, that basically had all the support that I wanted, including a <a href="http://download.oracle.com/javase/1,5.0/docs/api/java/util/LinkedHashMap.html">LinkedHashMap</a> implementation that can be used to implement a <a href="http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used">LRU cache</a>, just like good old java! The LRU feature is going to help me to remove &#8220;old&#8221; tags, keeping the memory required to process the tags within reasonable limits.</p>
<p>To make the first test succeed, only a few lines of code are needed:</p>
<pre class="brush: jscript; title: ; notranslate">
js_cols.require('js_cols.LinkedHashMap');
function TagCounter(maxSize) {
	this.tagCounts = new js_cols.LinkedHashMap(maxSize, true);
};
TagCounter.prototype.add = function (tag) {
	if (this.tagCounts.contains(tag)) {
		this.tagCounts.insert(tag, this.tagCounts.get(tag) + 1);
	} else {
		this.tagCounts.insert(tag,1);
	}
};
TagCounter.prototype.map = function () {
	return this.tagCounts;
};
</pre>
<p>In the end, however, we want the map method to return only the most popular tags, while our counter should keep track of a longer list. To implement this, we need two steps:</p>
<ol>
<li>First we need to sort the tags by their number of appearances in descending order, keeping in mind that multiple tags can have the same number.</li>
<li>Then we need to take the top x most popular tags.</li>
</ol>
<p>The test:</p>
<pre class="brush: jscript; title: ; notranslate">
...
    &quot;test should return limited sized map&quot;: function () {
    	var tc = new TagCounter(3);
    	tc.add(&quot;my-old-tag&quot;);
    	tc.add(&quot;my-old-tag&quot;);
    	tc.add(&quot;my-old-tag&quot;);
    	assertSame(tc.map(2), [[&quot;my-old-tag&quot;, 3]]);
    	tc.add(&quot;my-first-tag&quot;);
    	tc.add(&quot;my-first-tag&quot;);
    	assertSame(tc.map(2), [[&quot;my-old-tag&quot;, 3], [&quot;my-first-tag&quot;, 2]]);
    	tc.add(&quot;my-second-tag&quot;);
    	assertSame(tc.map(2), [[&quot;my-old-tag&quot;, 3], [&quot;my-first-tag&quot;, 2]]);
    	tc.add(&quot;my-third-tag&quot;);
    	assertSame(tc.map(2), [[&quot;my-first-tag&quot;, 2], [&quot;my-third-tag&quot;, 1]]);
    }
  });

  function assertSame(map, expected) {
	  var keys = map.getKeys();
	  assert.areEqual(expected.length, keys.length);
	  for(var i=0,len=expected.length; value=expected[i], i&lt;len; i++) {
		  assert.areEqual(value[0], keys[i]);
		  assert.areEqual(value[1], map.get(value[0]));
	  }
  };
...
</pre>
<p>In the test we now add a method assertSame to make it easier to express our expectations of the map method: The map should contain the expected number of tags with their counts in the right order. Therefor the expectation is a list of [tag, count]-tuples.</p>
<p>We can again use the collection library classes to implement this: The RedBlackMultiMap class implements a key-sorted map that allows multiple values for the same key. </p>
<pre class="brush: jscript; title: ; notranslate">
TagCounter.prototype.map = function (opt_size) {
	var orderedMap = new js_cols.RedBlackMultiMap(function (a,b) {return b-a;});
	this.tagCounts.forEach(orderedMap.insert, orderedMap);
	var result = new js_cols.LinkedHashMap();
	if (opt_size) {
		var i = 0;
		orderedMap.forEach(function (value, key) {
			if (i &lt; opt_size) {
				result.insert(value, key);
			}
			i++;
		});
	} else {
		orderedMap.forEach(result.insert, result);
	}
	return result;
};
</pre>
<p>On line 2 the RedBlackMultiMap constructor is used with a comparator function that will invert the natural ordering of numbers. This way we sort in descending order.<br />
On line 3 all items of the tagCount map are inserted into the orderedMap reversing the key-value relation. The fact that the forEach method take a function that has the value as the first and the key as the second argument (which would usually be confusing) now appears a handy feature!<br />
On lines 4 to 7, the key-value relation is again reversed, making sure to only take the top opt_size items from the map (when set).</p>
<h3>Conclusion</h3>
<p>Looking at the simplicity of the code and the tests, I would say that it is definitely possible to write well tested and documented JavaScript algorithms and data structures. I completely agree with my colleague, however, that such code is not often found in your run-of-the-mill web application project. Maybe it is time to start treating the JavaScript code in our projects more as Java code and make sure that it is properly structured and tested.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2011/06/23/writing-and-testing-data-structures-and-algorithms-in-javascript/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2011%2F06%2F23%2Fwriting-and-testing-data-structures-and-algorithms-in-javascript%2F&amp;title=Writing%20and%20testing%20data%20structures%20and%20algorithms%20in%20JavaScript" id="wpa2a_10"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2011/06/23/writing-and-testing-data-structures-and-algorithms-in-javascript/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Posting complex forms with RESTEasy &#8211; Part 2</title>
		<link>http://blog.xebia.com/2011/04/20/posting-complex-forms-with-resteasy-part-2/</link>
		<comments>http://blog.xebia.com/2011/04/20/posting-complex-forms-with-resteasy-part-2/#comments</comments>
		<pubDate>Wed, 20 Apr 2011 10:30:48 +0000</pubDate>
		<dc:creator>Maarten Winkels</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[RESTEasy]]></category>
		<category><![CDATA[collections]]></category>
		<category><![CDATA[form]]></category>
		<category><![CDATA[resteasy]]></category>

	<!-- AutoMeta Start -->
	<category>collectiontype</category>
	<category>ptype</category>
	<category>phonenumbers</category>
	<category>phonenumbers</category>
	<category>matcher</category>
	<category>generictype</category>
	<category>listforminjector</category>
	<category>emailaddress</category>
	<category>collectiontype</category>
	<category>ptype</category>
	<category>phonenumbers</category>
	<category>phonenumbers</category>
	<category>matcher</category>
	<category>generictype</category>
	<category>listforminjector</category>
	<category>emailaddress</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=6474</guid>
		<description><![CDATA[As promised in a previous blog, I&#8217;ll devote this blog to how to extend the RESTEasy framework with support for mapping form fields on object-graphs with complex associations, like lists and maps. These extensions have been reported to RESTEasy as two issues with patches. If you like these features, please vote for these issues. Extending [...]]]></description>
			<content:encoded><![CDATA[<p>As promised in <a href="http://blog.xebia.com/2011/03/posting-complex-forms-with-resteasy-part-1/">a previous blog</a>, I&#8217;ll devote this blog to how to extend the RESTEasy framework with support for mapping form fields on object-graphs with complex associations, like lists and maps.</p>
<p>These extensions have been reported to RESTEasy as <a href="https://issues.jboss.org/browse/RESTEASY-523">two</a> <a href="https://issues.jboss.org/browse/RESTEASY-524">issues</a> with patches. If you like these features, please vote for these issues.<br />
<span id="more-6474"></span><br />
Extending the existing framework (with the extensions from the previous blog) is not so hard and might be a lot easier then you think. The crux is finding the right mapping from names of the form fields to the complex structures in the Java objects.</p>
<p>A form with these fields and values:</p>
<pre class="brush: plain; title: ; notranslate">
firstName=Maarten
lastName=Winkels
emailAddresses[0].emailAddress=me@xebia.com
emailAddresses[1].emailAddress=me@gmail.com
phoneNumbers[home].number=0306324178
phoneNumbers[work].number=+31 35 2356785
</pre>
<p>Could be mapped to the Java class below easily.</p>
<pre class="brush: java; title: ; notranslate">
public class Person {

	@FormParam(&quot;firstName&quot;)
	private String firstName;

	@FormParam(&quot;lastName&quot;)
	private String lastName;

	@NestedFormParams(&quot;emailAddresses&quot;)
	private List&lt;EmailAddress&gt; emailAddresses;

	@NestedFormParams(&quot;phoneNumbers&quot;)
	private Map&lt;String, PhoneNumber&gt; phoneNumbers;
}

public class EmailAddress {

	@FormParam(&quot;emailAddress&quot;)
	private String emailAddress;
}

public class PhoneNumber {

	@FormParam(&quot;number&quot;)
	private String number;
}
</pre>
<p>The mapping is quite simple. A list is mapped with its prefix appended with an index number between square brackets. A maps prefix is appended with the key between square brackets. As soon as a prefix is found, the rest of the &#8220;deserialization&#8221; is the same as for the address in the previous blog: Properties can be appended to the prefix with a dot as separator.</p>
<p>Now when the RESTEasy framework encounters a <span style="font-family: monospace; font-size: medium">@NestedFormParam</span>, it can look at the type of the property to find out how to interpret the form fields. It also needs to figure out the types of the elements in the collection. This is done in the <span style="font-family: monospace; font-size: medium">InjectorFactory</span> or its extenion.</p>
<pre class="brush: java; title: ; notranslate">
public class ExtendedInjectorFactory extends InjectorFactoryImpl {

	private final ResteasyProviderFactory providerFactory;

	public ExtendedInjectorFactory(ResteasyProviderFactory factory) {
		super(factory);
		this.providerFactory = factory;
	}

	public ValueInjector createParameterExtractor(Class injectTargetClass,
			AccessibleObject injectTarget, Class type, Type genericType,
			Annotation[] annotations, boolean useDefault) {
		NestedFormParams param = FindAnnotation.findAnnotation(annotations,
				NestedFormParams.class);
		if (param != null) {
			String prefix = param.value();
			if (genericType instanceof ParameterizedType) {
				ParameterizedType pType = (ParameterizedType) genericType;
				if (isA(List.class, pType)) {
					return new ListFormInjector(type,
							getTypeArgument(pType, 0), prefix, providerFactory);
				}
				if (isA(Map.class, pType)) {
					return new MapFormInjector(type, getArgumentType(pType, 0),
							getTypeArgument(pType, 1), prefix, providerFactory);
				}
			}
			return new NestedFormInjector(type, prefix, providerFactory);
		}
		return super.createParameterExtractor(injectTargetClass, injectTarget,
				type, genericType, annotations, useDefault);

	}

	private boolean isA(Class clazz, ParameterizedType pType) {
		return clazz.isAssignableFrom((Class) pType.getRawType());
	}

	private Class getTypeArgument(ParameterizedType pType, int index) {
		return (Class) pType.getActualTypeArguments()[index];
	}
}
</pre>
<p>By inspecting the genericType parameter, the InjectorFactory finds out which Injector to use to instantiate and populate the correct class. The <span style="font-family: monospace; font-size: medium">isA</span> method is a utility method to find out if a collection type has been encountered. To find out the type of the elements in the collection, the <span style="font-family: monospace; font-size: medium">getTypeArgument</span> method is used. For a map type property the key type is also needed. <b>Note that this implementation requires the collection to be parameterized with the concrete type of its elements!</b></p>
<p>The implementations of <span style="font-family: monospace; font-size: medium">ListFormInjector</span> and <span style="font-family: monospace; font-size: medium">MapFormInjector</span> are very similar and have a common superclass.</p>
<pre class="brush: java; title: ; notranslate">
public abstract class AbstractCollectionFormInjector&lt;T&gt; extends NestedFormInjector {

	private final Class collectionType;

	private final Pattern pattern;

	protected AbstractCollectionFormInjector(Class collectionType, Class genericType,
				String prefix, Pattern pattern, ResteasyProviderFactory factory) {
		super(genericType, prefix, factory);
		this.collectionType = collectionType;
		this.pattern = pattern;
	}

	public Object inject(HttpRequest req, HttpResponse res) {
		T result = createInstance(collectionType);
		for (String prefix : findPrefixes(req.getDecodedFormParameters())) {
			Matcher matcher = pattern.matcher(prefix);
			matcher.matches();
			String key = matcher.group(1);
			addTo(result, key, super.doInject(prefix, req, res));
		}
		if (empty(result)) {
			return null;
		}
		return result;
	}

	private Set&lt;String&gt; findPrefixes(MultivaluedMap&lt;String, String&gt; parameters) {
		final HashSet&lt;String&gt; result = new HashSet&lt;String&gt;();
		for (String parameterName : parameters.keySet()) {
			final Matcher matcher = pattern.matcher(parameterName);
			if (matcher.lookingAt() &amp;&amp; hasValue(parameters.get(parameterName))) {
				result.add(matcher.group(0));
			}
		}
		return result;
	}

	protected abstract T createInstance(Class collectionType);

	protected abstract void addTo(T collection, String key, Object value);

	protected abstract boolean empty(T result);
}
</pre>
<p>The idea of this class is quite simple:</p>
<ol>
<li>First all matches in the form field names for the matcher are gathered. If the form contains fields like &#8216;phoneNumbers[home].number&#8217;, &#8216;phoneNumbers[home].extension&#8217; and &#8216;phoneNumbers[work].number&#8217; and the pattern is &#8216;phoneNumbers[(.*)]&#8216;, then the prefixes &#8216;phoneNumbers[home]&#8216; and &#8216;phoneNumbers[work]&#8216; are found. This is done in the <span style="font-family: monospace; font-size: medium">findPrefixes</span> method.</li>
<li>Now for each prefix the key is extracted. This is the part of the prefix that matched the first group. In the above example the first key would be <span style="font-family: monospace; font-size: medium">home</span> and the second would be <span style="font-family: monospace; font-size: medium">work</span>.</li>
<li>For each prefix an instance of the required element type is constructed by using the functionality in the <span style="font-family: monospace; font-size: medium">NestedFormInjector</span>.</li>
<li>All instances are collected in a collection, which is the end result of this injector.</li>
</ol>
<p>There are three parts of this procedure that need to be adapted for the specific collection type. Let&#8217;s look at the <span style="font-family: monospace; font-size: medium">ListFormInjector</span>.</p>
<pre class="brush: java; title: ; notranslate">
public class ListFormInjector extends AbstractCollectionFormInjector&lt;List&gt; {

	public ListFormInjector(Class collectionType, Class genericType,
				String prefix, ResteasyProviderFactory factory) {
		super(collectionType, genericType, prefix,
				Pattern.compile(&quot;^&quot; + prefix + &quot;\\[(\\d+)\\]&quot;), factory);
	}

	protected List createInstance(Class collectionType) {
		return new ArrayList();
	}

	protected void addTo(List collection, String key, Object value) {
		collection.add(Integer.parseInt(key), value);
	}

	protected boolean empty(List result) {
		return result.isEmpty();
	}
}
</pre>
<p>This is a very simple implementation. The most important part is probably the construction of the pattern at line 6. The pattern consists of the prefix and a number between square brackets. This number is later used as index into the list at line 14, where a new element is added to the list.</p>
<p>The implementation for maps is a little more complicated, since the key value has to be converted to an object as well. For this we use the <span style="font-family: monospace; font-size: medium">StringParameterInjector</span> of RESTEasy. An instance of this class can be used to convert a <span style="font-family: monospace; font-size: medium">String</span> to an instance of the required type.</p>
<pre class="brush: java; title: ; notranslate">
public class MapFormInjector extends AbstractCollectionFormInjector&lt;Map&gt; {

	private final StringParameterInjector keyInjector;

	public MapFormInjector(Class collectionType, Class keyType,
				Class valueType, String prefix, ResteasyProviderFactory factory) {
		super(collectionType, valueType, prefix,
				Pattern.compile(&quot;^&quot; + prefix + &quot;\\[([a-zA-Z_]+)\\]&quot;), factory);
		keyInjector = new StringParameterInjector(keyType, keyType,
				null, Form.class, null, null, new Annotation[0], factory);
	}

	protected Map createInstance(Class collectionType) {
		if (collectionType.isAssignableFrom(LinkedHashMap.class)) {
			return new LinkedHashMap();
		}
		if (collectionType.isAssignableFrom(TreeMap.class)) {
			return new TreeMap();
		}
		throw new RuntimeException(&quot;Unsupported collectionType: &quot; + collectionType);
	}

	protected void addTo(Map collection, String key, Object value) {
		collection.put(keyInjector.extractValue(key), value);
	}

	protected boolean empty(Map result) {
		return result.isEmpty();
	}
}
</pre>
<p>The pattern used here is quite strict: Only letters and underscores are allowed. This restricts the possibilities for the key values in the map. In some situations this might be to restrictive.</p>
<h3>Conclusion</h3>
<p>With a few classes we have extended the RESTEasy framework to be able to support mapping form fields to collections. Th required classes are attached to this blog in a <a href='http://blog.xebia.com/wp-content/uploads/2011/04/resteasy-example.zip'>zip file</a> as a Maven project. Feel free to use it in your own projects.<br />
I think this would be a good extension of RESTEasy, but so far the patches have not been accepted by the developers. If you like this extension, please vote for the issues mentioned in the beginning of this blog.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2011/04/20/posting-complex-forms-with-resteasy-part-2/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2011%2F04%2F20%2Fposting-complex-forms-with-resteasy-part-2%2F&amp;title=Posting%20complex%20forms%20with%20RESTEasy%20%26%238211%3B%20Part%202" id="wpa2a_12"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2011/04/20/posting-complex-forms-with-resteasy-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to use annotations for configuration</title>
		<link>http://blog.xebia.com/2011/04/15/how-to-use-annotations-for-configuration/</link>
		<comments>http://blog.xebia.com/2011/04/15/how-to-use-annotations-for-configuration/#comments</comments>
		<pubDate>Fri, 15 Apr 2011 22:34:38 +0000</pubDate>
		<dc:creator>Maarten Winkels</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[jackson]]></category>
		<category><![CDATA[resteasy]]></category>
		<category><![CDATA[Seam]]></category>

	<!-- AutoMeta Start -->
	<category>objectmapper</category>
	<category>annotationintrospector</category>
	<category>ejbexception</category>
	<category>jackson</category>
	<category>customobjectmapper</category>
	<category>objectmapper</category>
	<category>annotationintrospector</category>
	<category>ejbexception</category>
	<category>jackson</category>
	<category>customobjectmapper</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=6460</guid>
		<description><![CDATA[In the java world we have been using and getting used to annotations since Java 1.5. Although there were some critical voices at first, I think most of us have come around and are using annotations now quite extensively. In my experience annotations are mostly used on POJO domain classes to configure frameworks like Hibernate, [...]]]></description>
			<content:encoded><![CDATA[<p>In the java world we have been using and getting used to annotations since Java 1.5. Although there were <a href="http://blog.xebia.com/2007/01/28/a-pojo-with-annotations-is-not-plain/">some</a> <a href="http://blog.xebia.com/2007/04/03/ejb-3-annotations-to-the-max/">critical</a> <a href="http://willcode4beer.blogspot.com/2007/12/annotations-good-bad-and-ugly.html">voices</a> at first, I think most of us have come around and are using annotations now quite extensively. In my experience annotations are mostly used on POJO domain classes to configure frameworks like <a href="http://www.hibernate.org/">Hibernate</a>, <a href="http://www.springsource.org/">Spring</a> and <a href="http://www.seamframework.org/">Seam</a> and <a href="http://xstream.codehaus.org/">many</a> <a href="http://jaxb.java.net/">other</a> <a href="http://www.testng.org/">frameworks</a> to be able to handle the custom objects correctly.</p>
<p>There are as many different approaches to this as there are implementations. In this blog I try to identify a few of the better approaches and a few of the poorer ones. The blog is not so much meant as a critique on the frameworks that the examples are taken from, but more as a guide to designing your own annotations whenever you might be faced with that task.<br />
<span id="more-6460"></span></p>
<h3>Prime examples: JPA annotations</h3>
<p>The best examples of using annotations for configuration &#8211; both good and bad &#8211;  can be found in JPA Entity classes.</p>
<pre class="brush: java; title: ; notranslate">
@Entity
@Table(name=&quot;person&quot;)
public class Person {

  @Id
  @GeneratedValue(strategy=SEQUENCE)
  @Column(name = &quot;personId&quot;)
  private Long id;

  @Valid @NotEmpty
  @OneToMany(cascade = CascadeType.ALL)
  @JoinColumn(name = &quot;personId&quot;, nullable = false)
  @org.hibernate.annotations.Cascade(CascadeType.DELETE_ORPHAN)
  @org.hibernate.annotations.IndexColumn(name = &quot;position&quot;)
  private List&lt;Address&gt; addresses = new ArrayList&lt;Address&gt;();
  ...
}
</pre>
<p>What a wealth of annotations! And in such a few lines of code. Anybody that has dealt with this type of code before however, will testify that this example is not overly complex at all. You&#8217;ll find this ind of code all over.</p>
<p>To start with, let&#8217;s say that I think this type of coding has been extremely successful. So regardless whether we find the usage of annotations in this example recommendable or not, if you work with Java code, you&#8217;ll be reading and writing a lot of code like this, so understanding it is imperative. However success is just one of the indicators for quality and it is always good to think about how things can be improved.</p>
<h3>A perfect annotation</h3>
<p>Of course there is no such thing as a perfect annotation. But as a general rule of thumb a good annotation should <i>describe</i> the annotated element and be meaningful <i>outside its intended context</i>. This last requirement is a little bit vague. I hope it will become more clear once we look at some examples.</p>
<p>Annotations are very often used as a convenient means of configuration. This type of usage breaks the above rule for &#8216;perfect annotations&#8217;, but they are very convenient and very widely used. Drawbacks of this type of usage are:</p>
<ol>
<li>To change the configuration the source code needs to be recompiled.</li>
<li>The annotations (and thus their containing packages and often all of the framework code) need to be on the classpath for compilation and running.</li>
<li>Only one configuration can (usually) be specified. Most frameworks allow for a different means of configuration to circumvent this.</li>
</ol>
<p>&#8230;but these drawbacks do not mean that this type of usage has been less successful in the wild. On the contrary! There are however ways to design frameworks so that they can be configured by annotations that are not impacted by these drawbacks.</p>
<p>Let&#8217;s look at the example above in the light of these </p>
<ol>
<li>The <span style="font-family: monospace">@Entity</span> annotation specifies that instances of this class should contains data that is to be persisted. It describes how the class is intended. It also allows several frameworks to operate on it.</li>
<li>The <span style="font-family: monospace">@Table</span> annotation is pure configuration. It does not describe anything about this class and is tightly bound to its context: Databases.</li>
<li>The <span style="font-family: monospace">@Valid</span> and <span style="font-family: monospace">@NotEmpty</span> annotations describe features of <i>valid</i> instances of this class. They are however quite tightly bound to their context: data validation.</i>
</ol>
<p>For each of the annotations in the example such a analysis can be made. It is interesting to think about how <i>useful</i> the annotations are in relation how <i>perfect</i> they are: The <span style="font-family: monospace">@Entity</span> annotation, although being almost perfect is, is actually superfluous, because it will never be used without the <span style="font-family: monospace">@Table</span> annotation. The <span style="font-family: monospace">@Valid</span> and <span style="font-family: monospace">@NotEmpty</span> annotations are much more useful: They allow very powerful cross-cutting concerns to be implemented with very little code, configuration or dependency of application code on framework code, making it easy to test and reuse this code.</p>
<h3>Configuration annotation patterns in the wild</h3>
<h4> The Worst</h4>
<p>All this dribble about perfect annotations is nice and dandy, but where does it lead us? Maybe it is better to look at the other end of the spectrum, where we find the very worst of annotations:</p>
<pre class="brush: java; title: ; notranslate">
  @XmlJavaTypeAdapter(CurrencyAdapter.class)
  private BigDecimal price;
</pre>
<p>This <a href="http://download.oracle.com/javaee/5/api/javax/xml/bind/annotation/adapters/XmlJavaTypeAdapter.html">JAXB annotation</a>, used to configure the way a value is represented in XML, ties the implementation of a framework interface to the field on the domain class we&#8217;re trying to configure the framework for. We could as well implement the interface in the class itself!</p>
<h4> Better&#8230; Level of indirection</h4>
<p>A better pattern can be found in the seam framework for <a href="http://docs.jboss.org/seam/latest/reference/en-US/html_single/#d0e5568">configuring interceptors</a>. The following code configures an interceptor around a business method to measure the time it takes to complete.</p>
<pre class="brush: java; title: ; notranslate">
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Interceptors(SeamTimingInterceptor.class)
public @interface MeasureCalls {}
</pre>
<pre class="brush: java; title: ; notranslate">
...
	@MeasureCalls
	public void someBusinessMethod() {
		...
	}
...
</pre>
<pre class="brush: java; title: ; notranslate">
@Interceptor(around = {
	BijectionInterceptor.class,
	...
	SeamInterceptor.class,
})
public class SeamTimingInterceptor {

	@AroundInvoke
	public Object timeCall(InvocationContext invocation) throws Exception {
		long t0 = System.nanoTime();
		try {
			return invocation.proceed();
		} finally {
			long dt = System.nanoTime() - t0;
			// Log time.
		}
	}
}
</pre>
<p>The first annotation just defines a cross-cutting feature that we would like to implement in our application. We can easily use it in our application as shown by the second fragment.</p>
<p>Coming to the last code fragment, the actual implementation of the interceptor, i feel that the framework designers went a little overboard and were too annotation-happy: The interceptor could have simply implemented an interface:</p>
<pre class="brush: java; title: ; notranslate">
public interface  AroundMethodInterceptor {
	Object aroundInvoke(InvocationContext invocation);
}
</pre>
<p>This would have made the contract for an interceptor much clearer.</p>
<p>It could also help solve the other problem with this implementation: Now, the business class needs the annotation to compile, the annotation needs the interceptor and the interceptor needs the framework classes. From this perspective, the extra level of indirection has not helped a bit.</p>
<h4>Best&#8230; Classpath scanning and interfaces</h4>
<p>Another approach that is quite elegant is the JAX-RS approach to extending the framework through <a href="http://jackson.codehaus.org/javadoc/jax-rs/1.0/javax/ws/rs/ext/Provider.html">Provider</a>s and the <a href="http://www.jboss.org/resteasy">RESTEasy</a> implementation for it. The code below automatically registers an exception mapper, which integrates with the framework and is used to handle EJB exceptions coming from resource methods.</p>
<pre class="brush: java; title: ; notranslate">
@Provider
public class EJBExceptionMapper implements ExceptionMapper&lt;EJBException&gt; {

	@Context
	private Providers providers;

	@Override
	public Response toResponse(EJBException exception) {
		while (exception.getCause() != null
				&amp;&amp; exception.getCause() instanceof EJBException) {
			exception = (EJBException) exception.getCause();
		}
		Exception cause = exception.getCausedByException();
		ExceptionMapper delegate = providers.getExceptionMapper(cause.getClass());
		if (delegate != null) {
			return delegate.toResponse(cause);
		} else {
			return ExceptionUtil.serverError(cause.getMessage());
		}
	}
}
</pre>
<p>The good thing here is that the framework will scan for the annotation and then register the class according to its interface it implements.</p>
<p>Another interesting aspect is the <span style="font-family: monospace">@Context</span> annotation, that basically works as an injector point.</p>
<h4>Extensions for custom annotations</h4>
<p>This mechanism can be used to configure the RESTEasy framework to handle custom annotations for custom serialization. <a href="http://jackson.codehaus.org/">Jackson</a> has a similar mechanism like JAXB for configuring the way a field is seriaized with the <a href="http://jackson.codehaus.org/1.7.0/javadoc/org/codehaus/jackson/map/annotate/JsonSerialize.html">@JsonSerializer</a> annotation. Unfortunately this has the same drawbacks. A better approach can be implemented using the Provider mechanism on the Jackson framework itself.</p>
<pre class="brush: java; title: ; notranslate">
@Provider
public class ObjectMapperResolver implements ContextResolver&lt;ObjectMapper&gt; {

	private AnnotationIntrospector annotationIntrospector;

	public ObjectMapper getContext(Class&lt;?&gt; type) {
		return new CustomObjectMapper();
	}

	class CustomObjectMapper extends ObjectMapper {

		/**
		 * Constructor.
		 */
		public CustomObjectMapper() {
			super(null, null, null,
					new SerializationConfig(
						DEFAULT_INTROSPECTOR,
						pair(annotationIntrospector,DEFAULT_ANNOTATION_INTROSPECTOR),
						STD_VISIBILITY_CHECKER, null),
					new DeserializationConfig(DEFAULT_INTROSPECTOR,
						pair(annotationIntrospector,DEFAULT_ANNOTATION_INTROSPECTOR),
						STD_VISIBILITY_CHECKER, null)
					);
		}
	}
}
</pre>
<p>The above class &#8216;provides&#8217; the Jackson framework with a custom <span style="font-family: monospace">ObjectMapper</span>. This is done automatically, because the class is annotated with <span style="font-family: monospace">@Provider</span> and implements <span style="font-family: monospace">ContextResolver&lt;ObjectMapper></span>. Now the RESTEasy framework recognizes this as a part of the framework that will provide a <span style="font-family: monospace">ObjectMapper</span> to inject into a <span style="font-family: monospace">@Context</span> injection point. The Jackson framework uses the same injection point to find a <span style="font-family: monospace">ObjectMapper</span> to use for serialization.</p>
<p>Now how do we get it to recognize our own annotations? The answer is given by the code below, which is used in the custom <span style="font-family: monospace">ObjectMapper</span>.</p>
<pre class="brush: java; title: ; notranslate">
public class CustomAnnotationInspector extends NopAnnotationIntrospector {

	private Map&lt;Class&lt;? extends Annotation&gt;, String&gt; serializerComponents =
		new HashMap&lt;Class&lt;? extends Annotation&gt;, String&gt;();

	@Override
	public Object findSerializer(Annotated am, BeanProperty bp) {
		if (property != null) {
			for (Annotation annotation : bp.getMember().getAnnotated().getAnnotations()) {
				String name = serializerComponents.get(annotation.annotationType());
				if (name != null) {
					return Component.getInstance(name);
				}
			}
		}
		return super.findSerializer(am, bp);
	}
}
</pre>
<p>This can be used as shown below, when a serializer for the <span style="font-family: monospace">@Currency</span> is configured in the <span style="font-family: monospace">seriliazerComponents</span> map. (We use this in combination with the Seam framework for configuration).</p>
<pre class="brush: java; title: ; notranslate">
@Target({FIELD, METHOD})
@Retention(RUNTIME)
public @interface Currency {}

...
	@Currency
	BigInteger price;
...
</pre>
<h3>Conclusion</h3>
<p>In this blog I&#8217;ve shown a number of patterns for configuring frameworks using annotations. I&#8217;ve also shown some useful classes for extending the RESTEasy and Jackson  frameworks with support for custom annotations. I hope these examples will inspire you to write your own perfect and useful annotations.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2011/04/15/how-to-use-annotations-for-configuration/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2011%2F04%2F15%2Fhow-to-use-annotations-for-configuration%2F&amp;title=How%20to%20use%20annotations%20for%20configuration" id="wpa2a_14"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2011/04/15/how-to-use-annotations-for-configuration/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Posting complex forms with RESTEasy &#8211; Part 1</title>
		<link>http://blog.xebia.com/2011/03/18/posting-complex-forms-with-resteasy-part-1/</link>
		<comments>http://blog.xebia.com/2011/03/18/posting-complex-forms-with-resteasy-part-1/#comments</comments>
		<pubDate>Fri, 18 Mar 2011 21:18:24 +0000</pubDate>
		<dc:creator>Maarten Winkels</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[RESTEasy]]></category>
		<category><![CDATA[form post]]></category>
		<category><![CDATA[resteasy]]></category>

	<!-- AutoMeta Start -->
	<category>personresource</category>
	<category>nestedforminjector</category>
	<category>addformheader</category>
	<category>personresource</category>
	<category>nestedforminjector</category>
	<category>addformheader</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=6370</guid>
		<description><![CDATA[RESTEasy is a Framework for building RESTful applications in Java. In this blog I will show how to easily build RESTful webservices that accept data from an HTML Form. We will also explore the possibilities to extend RESTEasy to handle more complex cases. Note: All source code in this post is attached as a zipped [...]]]></description>
			<content:encoded><![CDATA[<p>RESTEasy is a Framework for building RESTful applications in Java. In this blog I will show how to easily build RESTful webservices that accept data from an HTML Form. We will also explore the possibilities to extend RESTEasy to handle more complex cases.<br />
<span id="more-6370"></span><br />
<b>Note:</b> All source code in this post is <a href="http://blog.xebia.com/wp-content/uploads/2011/03/resteasy-example.zip">attached as a zipped Maven project</a>.</p>
<h3>Simple Example</h3>
<p>So let&#8217;s look at a very simple example:</p>
<pre class="brush: java">
public class Person {
	private String firstName;
	private String lastName;
}

@Path("/person")
public class PersonResource {
	private PersonRepository repository;

	@POST
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Produces(MediaType.APPLICATION_JSON)
	public Person savePerson(Person person) {
		return repository.save(person);
	}
}
</pre>
<p>The intent of these two classes should be pretty clear: We want to expose the <span style="font-family: monospace; font-size: medium">savePerson</span> method as a WebService, accept data from a HTML form and produce JSON. The annotations used on the <span style="font-family: monospace; font-size: medium">PersonResource</span> are <a href="http://jcp.org/en/jsr/detail?id=311">JAX-RS annotations</a>.</p>
<p>Now notice that we both accept and return a <span style="font-family: monospace; font-size: medium">Person</span> object in the service method. We expect the RESTEasy framework to handle the unmarshalling from the Form fields and the marshalling to JSON. Luckily JAX-RS also comes with some handy annotations for this: The <a href="http://jsr311.java.net/nonav/releases/1.1/javax/ws/rs/FormParam.html"><span style="font-family: monospace; font-size: medium">@FormParam</span> annotation</a> lets you define which Form field to map to which parameter or field. Unfortunately the JAX-RS specification does not talk about mapping forms to rich objects, so the signature for our service method would become
<pre class="brush: java">
	public Person savePerson (
			@FormParam("firstName") String firstName,
			@FormParam("lastName") String lastName,
			...
			) {
</pre>
<p> which would become rather large and unwieldy rather soon, when the form has to include all the usual name and address fields.</p>
<p>This is where RESTEasy comes to the rescue with the <a href="http://docs.jboss.org/resteasy/docs/2.0.0.GA/javadocs/org/jboss/resteasy/annotations/Form.html"><span style="font-family: monospace; font-size: medium">@Form</span> annotation</a>. This annotation tells the RESTEasy framework to map the entire form onto a parameter object, relieving us from the task to specify all form fields in the parameter list of the service method. The code thus becomes:</p>
<pre class="brush: java">public class Person {
	@FormParam("firstName") private String firstName;
	@FormParam("lastName") private String lastName;
}

@Path("/person")
public class PersonResource {
	private PersonRepository repository;

	@POST
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Produces(MediaType.APPLICATION_JSON)
	public Person savePerson(@Form Person person) {
		return repository.save(person);
	}
}</pre>
<h3>How to test this?</h3>
<p>With these two simple classes, we&#8217;re done implementing our simple requirements. But how do we test this? RESTEasy comes with a JUnit extension that is very useful to test Resources.</p>
<pre class="brush: java">@RunWith(MockitoJUnitRunner.class)
public class PersonResourceTest extends BaseResourceTest{

	private PersonResource resource;
	@Mock private PersonRepository repository;

	@Before
	public void setupResource() {
		MockitoAnnotations.initMocks(getClass());
		resource = new PersonResource();
		resource.setRepository(repository);
(1)		dispatcher.getRegistry().addSingletonResource(resource);
	}

	@After
	public void removeResource() {
		dispatcher.getRegistry().removeRegistrations(PersonResource.class);
	}	

	@Test
	public void shouldSavePerson() throws Exception {
(2)		MockHttpRequest request = post("/person");
		request.addFormHeader("firstName", "Maarten");
		request.addFormHeader("lastName", "Winkels");

(3)		ArgumentCaptor&lt;Person&gt; personCaptor = ArgumentCaptor.forClass(Person.class);
		when(repository.save(personCaptor.capture())).thenAnswer(new ArgumentAnswer&lt;Person&gt;(0));

		MockHttpResponse response = new MockHttpResponse();
(4)		dispatcher.invoke(request, response);

		verify(repository).save(any(Person.class));
(5)		Person person = capturePerson.getLastValue();
		assertEquals("Maarten", person.getFirstName());
		assertEquals("Winkels", person.getLastName());

(6)		assertEquals(200, response.getStatus());
		assertEquals("{\"firstName\":\"Maarten\",\"lastName\":\"Winkels\"}", response.getContentAsString());
	}
}</pre>
<p>The test above is a true integration test as far as RESTEasy is concerned, in the sense that an HttpRequest is processed by the framework and triggers our <span style="font-family: monospace; font-size: medium">PersonResource</span> to produce a JSON response.</p>
<p>Mockito is used to be mock out the <span style="font-family: monospace; font-size: medium">PersonRepository</span> (which is not yet implemented), and to be able to check some behavior of the code in the test. Stepping through the code:</p>
<ol>
<li>The <span style="font-family: monospace; font-size: medium">PersonResource</span> with the mock for the repository is registered with the framework in the test. We need to register it as a singleton here, wince we have to prepare the resource with a mock. Notice that the class is removed in the <span style="font-family: monospace; font-size: medium">@After</span> method to ensure that the tests have no side-effects.</li>
<li>A <span style="font-family: monospace; font-size: medium">MockHttpRequest</span> is prepared to be processed with certain values.</li>
<li>The mock repository is setup to capture the argument coming into the request and to return the same argument as response. The <span style="font-family: monospace; font-size: medium">ArgumentAnswer</span> is a small extension of the Mockito/Hamcrest framework to enable the mock to return the parameter passed into the call on the mock as the return value.</li>
<li>The request is executed on the dispatcher, capturing the response in a <span style="font-family: monospace; font-size: medium">MockHttpResponse</span>.</li>
<li>The <span style="font-family: monospace; font-size: medium">Person</span> we captured is inspected to see that the values are copied from the request.</li>
<li>The response is inspected for return value and content.</li>
</ol>
<p>That was easy! We&#8217;ve integration tested our entire RESTful application without having to start a container!</p>
<h3>A little more complex: nested object structures and forms</h3>
<p>Let&#8217;s try something little more complex: Let&#8217;s assume the person has an address. We&#8217;ll code the test first:</p>
<pre class="brush: java">	@Test
	public void shouldSavePersonWithAddress() throws Exception {
		MockHttpRequest request = post("/person");
		request.addFormHeader("firstName", "Maarten");
		request.addFormHeader("lastName", "Winkels");
		request.addFormHeader("address.street", "Dorpsstraat");
		request.addFormHeader("address.houseNumber", "19a");

		ArgumentCaptor&lt;Person&gt; personCaptor = ArgumentCaptor.forClass(Person.class);
		when(repository.save(personCaptor.capture())).thenAnswer(new ArgumentAnswer&lt;Person&gt;(0));

		MockHttpResponse response = new MockHttpResponse();
		dispatcher.invoke(request, response);

		verify(repository).save(any(Person.class));
		Person person = capturePerson.getLastValue();
		assertEquals("Maarten", person.getFirstName());
		assertEquals("Winkels", person.getLastName());
		assertEquals("Dorpsstraat", person.getAddress().getStreet());
		assertEquals("19a", person.getAddress().getHouseNumber());

		assertEquals(200, response.getStatus());
		assertEquals("{\"firstName\":\"Maarten\",\"lastName\":\"Winkels\",\"address\":{\"street\":\"Dorpsstraat\",\"houseNumber\":\"19a\"}}", response.getContentAsString());
	}</pre>
<p>As you can see from the test, a person now has an address and we expect the form fields that start with &#8220;address.&#8221; to be mapped to the fields in the <span style="font-family: monospace; font-size: medium">Address</span> class. In a sense, the form is now mapped to the <i>nested</i> object structure of person and address. Unfortunately neither JAX-RS nor RESTEasy has support for this. (RESTEasy does support a <span style="font-family: monospace; font-size: medium">@Form</span> annotation in a <span style="font-family: monospace; font-size: medium">@Form</span> mapped parameter class, but it does not support specifying a prefix, thus only supporting a single nested object of the same type.)</p>
<p>So we introduce a new annotation to indicate that a field is mapped to a part of the form fields: </p>
<pre class="brush: java">public class Person {
...
	@NestedFormParams("address")
	private Address address;
...
}</pre>
<p>To the RESTEasy framework, this new annotation means a new way of injecting values into objects, which is rather similar to how values are injected into <span style="font-family: monospace; font-size: medium">@Form</span> annotated parameters. <span style="font-family: monospace; font-size: medium">*Injector</span>s are created by an <span style="font-family: monospace; font-size: medium">InjectorFactory</span>. The <span style="font-family: monospace; font-size: medium">ExtendedInjectorFactory</span> below extends the RESTEasy <span style="font-family: monospace; font-size: medium">InjectorFactoryImpl</span> to make RESTEasy aware of the new annotation.</p>
<pre class="brush: java">public class ExtendedInjectorFactory extends InjectorFactoryImpl{

	private final ResteasyProviderFactory factory;

	public ExtendedInjectorFactory(ResteasyProviderFactory factory) {
		super(factory);
		this.factory = factory;
	}

	@Override
	public ValueInjector createParameterExtractor(Class injectTargetClass, AccessibleObject injectTarget, Class type, Type genericType, Annotation[] annotations, boolean useDefault) {
		NestedFormParams param = FindAnnotation.findAnnotation(annotations, NestedFormParams.class);
		if (param != null) {
			return new NestedFormInjector(type, factory, param.value());
		}
		return super.createParameterExtractor(injectTargetClass, injectTarget, type, genericType, annotations, useDefault);
	}

}</pre>
<p>In the test, the new <span style="font-family: monospace; font-size: medium">InjectorFactory</span> is registered with the <span style="font-family: monospace; font-size: medium">ProviderFactory</span>:</p>
<pre class="brush: java; title: ; notranslate">	@Before
	public void setupResource() {
		getProviderFactory().setInjectorFactory(new ExtendedInjectorFactory(getProviderFactory()));
		...
	}</pre>
<p>Whenever a <span style="font-family: monospace; font-size: medium">NestedFormParams</span> annotation is found, a <span style="font-family: monospace; font-size: medium">NestedFormInjector</span> is created to handle the injection. Since the functionality is so similar to the <span style="font-family: monospace; font-size: medium">FormInjector</span>, it simply is an extension of that class.</p>
<pre class="brush: java">public class NestedFormInjector extends FormInjector {

	private final String prefix;

	public NestedFormInjector(Class&lt;?&gt; type, ResteasyProviderFactory factory, String prefix) {
		super(type, factory);
		this.prefix = prefix;
	}

	@Override
	public Object inject(HttpRequest request, HttpResponse response) {
		if (!containsPrefixedName(request.getDecodedFormParameters().keySet())) {
			return null;
		}
		return super.inject(new PrefixedFormFieldsHttpRequest(prefix, request), response);
	}

	private boolean containsPrefixedName(Set&lt;String&gt; keys) {
		for (String key : keys) {
			if (key.startsWith(prefix)) {
				return true;
			}
		}
		return false;
	}
}</pre>
<p>To understand how the <span style="font-family: monospace; font-size: medium">NestedFormInjector</span> works, one has to understand how the <span style="font-family: monospace; font-size: medium">FormInjector</span> works. The form injector is created for a specific type. It uses a <span style="font-family: monospace; font-size: medium">ConstructorInjector</span> to create an instance of that type and a <span style="font-family: monospace; font-size: medium">PropertyInjector</span> to inject other values into this instance. The injection of these values is carried out by other injectors. If a field in the class is annotated with an <span style="font-family: monospace; font-size: medium">@FormParam</span> annotation, the <span style="font-family: monospace; font-size: medium">FormInjector</span> is used to inject the value from the form parameter into the field.</p>
<p>The <span style="font-family: monospace; font-size: medium">NestedFormInjector</span> works by restricting the access of any form injectors that are used for it&#8217;s properties to form fields that start with the given prefix (and a dot). This is achieved by wrapping the original <span style="font-family: monospace; font-size: medium">HttpRequest</span> in an <span style="font-family: monospace; font-size: medium">PrefixedFormFieldHttpRequest</span>. Objects of this class wrap the original form fields in a map that will add the prefix on each look up. The code can be found in the attached ZIP file.</p>
<h3>Conclusion</h3>
<p>By extending a few of the core classes of the RESTEasy framework, we have added the functionality to map a HTTP form to a complex association of two classes. This can be really useful when complex forms are posted.<br />
A next step would be to map form fields to collections, lists or maps. I&#8217;ll write about that in a next post.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2011/03/18/posting-complex-forms-with-resteasy-part-1/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2011%2F03%2F18%2Fposting-complex-forms-with-resteasy-part-1%2F&amp;title=Posting%20complex%20forms%20with%20RESTEasy%20%26%238211%3B%20Part%201" id="wpa2a_16"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2011/03/18/posting-complex-forms-with-resteasy-part-1/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Regression Testing with an Agile Mindset</title>
		<link>http://blog.xebia.com/2010/11/05/regression-testing-with-an-agile-mindset/</link>
		<comments>http://blog.xebia.com/2010/11/05/regression-testing-with-an-agile-mindset/#comments</comments>
		<pubDate>Fri, 05 Nov 2010 14:07:09 +0000</pubDate>
		<dc:creator>Maarten Winkels</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Testing]]></category>

	<!-- AutoMeta Start -->
	<category></category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=5445</guid>
		<description><![CDATA[When applying agile methods to existing software development practices, it is often useful to start from the basics. For regression testing this boils down to: Regression testing ensures continuity of business functions. In an agile context it helps the team focus on the (new) functionality to develop in the sprint while maintaining overall stability. To [...]]]></description>
			<content:encoded><![CDATA[<p>When applying agile methods to existing software development practices, it is often useful to start from the basics. For regression testing this boils down to:</p>
<ol>
<li>Regression testing ensures <strong>continuity of business functions</strong>.</li>
<li>In an agile context it helps the team <strong>focus</strong> on the (new) functionality to develop in the sprint while maintaining overall stability.</li>
<li>To maximally utilize regression testing in an agile context, <strong>test automation</strong> and <strong>continuous execution</strong> should be applied.</li>
<li>It is important to realize the <strong>difference between functional tests and regression tests</strong> to avoid some common pitfalls.</li>
</ol>
<p><span id="more-5445"></span><br />
<strong>Regression testing ensures continuity of business functions</strong><br />
The target area of the regression test is the complete set of (end-to-end) business functions that a system encompasses. The same tests are executed repeatedly over time to ensure that the required behaviours of the system remain stable.<br />
In an agile context this means that regression test results are of great value to the product owner at the end of each sprint, when he has to evaluate and accept not only the newly developed functionality, but the overall functionality of the system after the changes have been made. Ideally, there should be no regression in the functionality of the system. In real-life, complex systems however, a trade off can be made between the immediate value of the new functionality and regression bugs that have (unintentionally) been introduced.<br />
But the Product Owner should be very careful! A zero-tolerance policy towards bugs is in the long run far more effective than accepting even small regressions for the sake of faster development. Therefore it is better to decrease the scope then to accept regression.</p>
<p>Of course expectations and sometimes entire tests have to be adapted as business functions change or new tests have to be added when additional functionality is developed. In an agile context, where change is continuous and gradual, changes to business functions should not be disruptive. Maintaining the regression test suites can be a relatively easy job.</p>
<p><strong>Focus on new functionality</strong><br />
One of the main success factors of the agile approach (specifically SCRUM) is, that it allows the entire team to focus on the functionality that has been planned for the current sprint. This focus allows the team to aim for the best quality of the solution in every aspect, be it architecture, design, implementation or testing. In a complex environment, you cannot expect a team to focus on a particular part while at the same time understanding the consequences and risks for the entire system. Regression tests provide a safety net for the team in this situation. Any areas of the environment that might have been missed in the analysis of the problem or the proposed solution, will be shown by the regression test provided that the coverage of the regression test suites is sufficient.</p>
<p><strong>Continuous automated regression tests give rapid feedback</strong><br />
To allow the team to respond efficiently to any findings from the regression tests, it is imperative that the regression tests are executed shortly after changes have been made. Late feedback means that it is harder to track the source of the unexpected behaviour, to analyse the error and to correct the implementation. The team might have moved on to implement other changes in other areas of the system, which means that it will take more effort to switch back to the area in which the problem was found. Since the problem did not surface during functional testing, it is very probable that the cause of the problem is of a more structural nature and the architecture and design of the solution have to be re-evaluated. Most likely new functional tests have to be added to ensure that the issues found are not just the tip of the iceberg.</p>
<p>The required rapid feedback can often only be achieved when the regression tests are executed fast and automatically. To this end regression tests need to be scripted and run on an automatic build environment.</p>
<p><strong>Regression test suite != sum(Functional test suites)</strong><br />
The purpose of functional tests is to explore the behaviour of specific business functions and highlight corner cases. As discussed above, the purpose of regression testing is to give and overall overview of the entire system. These two purposes are distinct and therefore functional test suites should not simply be used as regression tests.</p>
<p>In an agile context, functional tests are used to prove that the team has delivered the functionality that is planned for a sprint. The development of the functional test cases is part of the sprint in which the functionality is developed. The functional test cases are thus a basis for the product owner to accept the new functionality. In many agile teams I have seen that functional tests that have been developed for previous sprints are run in succession as regression tests for the current and coming sprints. Although this is an easy and cheap approach to build a regression test suite, there are a number of problems with this approach:</p>
<ol>
<li>Since the system is developed in iterative and evolutionary fashion, the same business functions are often changed and enhanced multiple times over many sprints. As a result many functional tests are written for the same business function. This means a lot of &#8220;test duplication&#8221;. Since the business function is changing, the old test scripts have to be adapted and the required effort will grow with every sprint.</li>
<li>At the same time, the value of the regression tests has not increased, since the same business function is being tested. The overall overview of the system has not improved, but rather been obfuscated by adding more data.</li>
<li>As a side effect it also takes longer to execute the regression tests and to analyse the results.</li>
</ol>
<p>Therefore it is better to work with (or towards) a smaller, relatively stable set of regression tests. This set should be constructed on the basis of knowledge of the business functions and of the technical implementation, to ensure sufficient but not superfluous coverage. It is thus the responsibility of the entire team.</p>
<p>So how does the team develop this set of regression tests?</p>
<ol>
<li>The product owner compiles a list of all business functions that should be included in the regression test. This can happen gradually over several sprints while the team learns what functions are important. Creating the tests can also be done gradually.</li>
<li>Functional tests in the sprint are basically &#8220;throw away&#8221; tests: They are not intended to be maintained for long. Perhaps you keep the tests so you can update and reuse some of them later.</li>
<li>Some functional tests can be upgraded to regression tests, when they cover certain business functions better then existing tests. The existing tests can then be taken out of the regression test suite.</li>
<li>Regression test scripts are updated in the sprint when necessary. This is part of the UserStory and should thus be taken into account when estimating.</li>
</ol>
<p><strong>Conclusions</strong></p>
<ol>
<li>Regression testing has an important role in Agile development. In addition to its usual purpose of proving stability, it helps the team focus on the functionality in the current sprint.</li>
<li>Although it is tempting to use the functional tests of the past sprints as regression tests for the current sprint, this will lead to an unwieldy regression test suite and will blur the purpose of the regression test suite by introducing a lot of duplication. In stead the regression test suite should be constructed to reflect the (most important) business processes.</li>
</ol>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2010/11/05/regression-testing-with-an-agile-mindset/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2010%2F11%2F05%2Fregression-testing-with-an-agile-mindset%2F&amp;title=Regression%20Testing%20with%20an%20Agile%20Mindset" id="wpa2a_18"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2010/11/05/regression-testing-with-an-agile-mindset/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Tweaking JAXB to generate better code</title>
		<link>http://blog.xebia.com/2009/09/02/tweaking-jaxb-to-generate-better-code/</link>
		<comments>http://blog.xebia.com/2009/09/02/tweaking-jaxb-to-generate-better-code/#comments</comments>
		<pubDate>Wed, 02 Sep 2009 21:03:07 +0000</pubDate>
		<dc:creator>Maarten Winkels</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[jaxb]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[xjb plugin]]></category>
		<category><![CDATA[XmlElementWrapper]]></category>

	<!-- AutoMeta Start -->
	<category>replies</category>
	<category>replies</category>
	<category>reply</category>
	<category>reply</category>
	<category>getreplies</category>
	<category>jaxb</category>
	<category>getreply</category>
	<category>xxew</category>
	<category>replies</category>
	<category>replies</category>
	<category>reply</category>
	<category>reply</category>
	<category>getreplies</category>
	<category>jaxb</category>
	<category>getreply</category>
	<category>xxew</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=3100</guid>
		<description><![CDATA[JAXB can be a real time saver when working on a project that uses XSD to describe interfaces implemented in Java. Sometimes, however, the generated code is not up to standard. I ran into a problem that seems very common and found a very elegant solution to it on the web. Yesterday, while working on [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://java.sun.com/developer/technicalArticles/WebServices/jaxb/">JAXB</a> can be a real time saver when working on a project that uses XSD to describe interfaces implemented in Java. Sometimes, however, the generated code is not up to standard. I ran into a problem that seems very common and found a very elegant solution to it on the web.<br />
<span id="more-3100"></span><br />
Yesterday, while working on the XML Schema for Document, I had to decide whether I would wrap collections in a surrounding element, like this:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;Document&gt;
...
  &lt;Replies&gt;
    &lt;Reply&gt;
      ...
    &lt;/Reply&gt;
    &lt;Reply&gt;
      ...
    &lt;/Reply&gt;
    ...
  &lt;/Replies&gt;
  ...
&lt;/Document&gt;
</pre>
<p>or I would just have a sequence of &lt;Reply>-elements directly under Document. I think the general consensus is to use wrapping elements, but I decided to base the design on another measure: What would the (Java) code look like that would be generated from the Schema by JAXB.</p>
<p>After configuring the <a href="https://jaxb.dev.java.net/jaxb-maven2-plugin/">maven-jaxb-plugin</a> into the project (which was really easy and it integrated out of the box with Eclipse through <a href="http://m2eclipse.sonatype.org/">M2Eclipse</a>), the Java code was a little disappointing: For every collection I would get the following structure:</p>
<pre class="brush: java; title: ; notranslate">
class Document {

  @XmlElement(name = &quot;Replies&quot;)
  private Replies replies;

  public Replies getReplies() {
    return replies;
  }

  public class Replies() {

    @XmlElement(name = &quot;Reply&quot;)
    private List&lt;Reply&gt; reply;

    public List&lt;Reply&gt; getReply() {
      return reply;
    }
  }
}
</pre>
<p>This would lead to the following usage pattern:</p>
<pre class="brush: java; title: ; notranslate">
  Document doc;
  ...
  doc.getReplies().getReply().add(new Reply(...));
</pre>
<p>which is in my opinion quite awful. I would expect there to be a simple collection structure:</p>
<pre class="brush: java; title: ; notranslate">
  Document doc;
  ...
  doc.getReplies().add(new Reply(...));
</pre>
<p>But whether I would use the wrapping element or not, I would still get the additional class.</p>
<p>There is a JAXB annotation that will help in this situation:</p>
<pre class="brush: java; title: ; notranslate">
  @XmlElementWrapper(name = &quot;replies&quot;)
  @XmlElement(name = &quot;reply&quot;)
  protected List&lt;Reply&gt; replies;
</pre>
<p>And this is exactly what we want, but how to tell the JAXB code generator to use that annotation?</p>
<p>After some googling around, I found <a href="http://www.conspicio.dk/blog/bjarne/jaxb-xmlelementwrapper-plugin" target="_new">this blog posting</a>, that provides a solution by using a custom plugin for XJB (the JAXB code generator). Configuring this in maven was quite easy:</p>
<ol>
<li>Add the plugin jar (which was unfortunately not available from a Maven repo) to the maven-jaxb-plugin dependencies.
<li>Add an &lt;args>-element to the plugin configuration with the -Xxew option to activate the plugin.
</ol>
<p>The final Maven configuration looks like this:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;plugin&gt;
  &lt;groupId&gt;com.sun.tools.xjc.maven2&lt;/groupId&gt;
  &lt;artifactId&gt;maven-jaxb-plugin&lt;/artifactId&gt;
  &lt;executions&gt;
    &lt;execution&gt;
      &lt;id&gt;jaxb-generate&lt;/id&gt;
      &lt;goals&gt;
        &lt;goal&gt;generate&lt;/goal&gt;
      &lt;/goals&gt;
    &lt;/execution&gt;
  &lt;/executions&gt;
  &lt;configuration&gt;
    &lt;includeSchemas&gt;
      &lt;includeSchema&gt;xsd/Document.xsd&lt;/includeSchema&gt;
    &lt;/includeSchemas&gt;
    &lt;strict&gt;true&lt;/strict&gt;
    &lt;verbose&gt;true&lt;/verbose&gt;
    &lt;args&gt;-Xxew&lt;/args&gt;
  &lt;/configuration&gt;
  &lt;dependencies&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;xew&lt;/groupId&gt;
      &lt;artifactId&gt;xew&lt;/artifactId&gt;
      &lt;version&gt;1.0.0&lt;/version&gt;
      &lt;scope&gt;runtime&lt;/scope&gt;
    &lt;/dependency&gt;
  &lt;/dependencies&gt;
&lt;/plugin&gt;
</pre>
<p>The generated code now uses a simple collection, so it looks much more usable.</p>
<p>One last problem is that the generated Replies class, that is now no longer used, is not removed from the code: A little clean up task that must have slipped the plugin developers mind.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2009/09/02/tweaking-jaxb-to-generate-better-code/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2009%2F09%2F02%2Ftweaking-jaxb-to-generate-better-code%2F&amp;title=Tweaking%20JAXB%20to%20generate%20better%20code" id="wpa2a_20"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2009/09/02/tweaking-jaxb-to-generate-better-code/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  blog.xebia.com/author/mwinkels/feed/ ) in 2.86635 seconds, on Feb 9th, 2012 at 4:25 pm UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on Feb 9th, 2012 at 5:25 pm UTC -->
