<?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>Tales From The Cloud &#187; software</title>
	<atom:link href="http://blog.newsplore.com/category/software/feed" rel="self" type="application/rss+xml" />
	<link>http://blog.newsplore.com</link>
	<description>Everything beta</description>
	<lastBuildDate>Sun, 05 Feb 2012 09:03:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Bootstrap your node.js project in the cloud</title>
		<link>http://blog.newsplore.com/2011/09/09/bootstrap-your-nodejs-project-in-the-cloud</link>
		<comments>http://blog.newsplore.com/2011/09/09/bootstrap-your-nodejs-project-in-the-cloud#comments</comments>
		<pubDate>Fri, 09 Sep 2011 09:32:10 +0000</pubDate>
		<dc:creator>Florin</dc:creator>
				<category><![CDATA[software]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[nodejs]]></category>

		<guid isPermaLink="false">http://blog.newsplore.com/?p=1753</guid>
		<description><![CDATA[So you have a great website idea and you want to build and bring that first version online as fast as you can. You figured that node.js is the way to go. You kick-off the development and after a couple of hours of hacking you realize that although you&#8217;re progressing at breakneck speed you&#8217;re missing [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="padding-right:0;margin-top:3px"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.newsplore.com%2F2011%2F09%2F09%2Fbootstrap-your-nodejs-project-in-the-cloud"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.newsplore.com%2F2011%2F09%2F09%2Fbootstrap-your-nodejs-project-in-the-cloud" height="61" width="51" /></a></div><p>So you have a great website idea and you want to build and bring that first version online as fast as you can. You figured that <a href="http://nodejs.org">node.js</a> is the way to go. You kick-off the development and after a couple of hours of hacking you realize that although you&#8217;re progressing at breakneck speed you&#8217;re missing a few important bits:</p>
<ul>
<li>- How do I better structure my project?</li>
<li>- I want to test this thing. I want unit tests, UI (headless browser) tests and public API tests (I want that API offering out too of course)</li>
<li>- I want proper CSS and html templating</li>
<li>- Looks like I need non-trivial request routing, I need more than the default provided</li>
</ul>
<p>Oh, and after you have all of this, you want to be able to deploy it to a node-ready cloud environment like <a href='http://heroku.com'>Heroku</a> without hassle.</p>
<p>Enter <a href='https://github.com/florind/bootstrap.js'>bootstrap.js</a>. </p>
<p><span id="more-1753"></span></p>
<p>It bootstraps the application structure, integrates technologies for templating, routing, etc. and as importantly, comes with the option of pushing the application to the cloud.</p>
<p><b>Project structure</b><br />
The project structure, influenced by <a href='http://stackoverflow.com/questions/5178334/folder-structure-for-a-nodejs-project'>this suggestion</a>  is:</p>
<pre>
controllers/
views/                &lt;-- view templates
public/               &lt;-- public files
public/stylesheets    &lt;-- stylus css files
spec/                 &lt;-- BDD tests and web service tests
test/                 &lt;-- unit tests
</pre>
<p>The bootstrapping also creates a git repo for your convenience.</p>
<p><b>Technologies</b><br />
Bootstrap.js comes integrated with:</p>
<ul>
<li>- <a href='http://expressjs.com/'>Express</a> framework for routing</li>
<li>- <a href='http://jade-lang.com'>Jade</a> template engine</li>
<li>- <a href='https://github.com/learnboost/stylus'>Stylus</a> CSS generator</li>
<li>- JQuery 1.5.2</li>
</ul>
<p><b>A word about testing</b><br />
Nodejs applications are particularly interesting from a testing perspective given the asynchronous nature of the language itself but I found that the tests are especially valuable when trying-out different technologies since testing is the best way to validate them. Bootstrap.js&#8217;s tests are structured to provide the more important aspects of application testing: there are basic unit, BDD and public API tests that are shipped along, giving the developer a starting point to add more tests in those areas as the development progresses. Look in the test/ and spec/ directories for them.</p>
<p><b>Cloud deployment</b><br />
Although the bootstrapping can be done locally, the more exciting option is to drop your web application in a hosted environment (and show it off your friends afterwards). There are currently two cloud environments supported: <a href='http://heroku.com'>Heroku</a> and Joyent&#8217;s <a>no.de</a>. Both have native node support and integrate with your code via git and both making a live service upgrade as easy as &#8220;git push&#8221;.</p>
<p><b>Do contribute</b><br />
I welcome your suggestions/improvements. Get and fork <a href='https://github.com/florind/bootstrap.js'>the code</a> for others to enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.newsplore.com/2011/09/09/bootstrap-your-nodejs-project-in-the-cloud/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Comparison of Places APIs</title>
		<link>http://blog.newsplore.com/2011/03/23/a-comparison-of-places-apis</link>
		<comments>http://blog.newsplore.com/2011/03/23/a-comparison-of-places-apis#comments</comments>
		<pubDate>Wed, 23 Mar 2011 21:31:55 +0000</pubDate>
		<dc:creator>Florin</dc:creator>
				<category><![CDATA[software]]></category>
		<category><![CDATA[Geo]]></category>
		<category><![CDATA[LBS]]></category>
		<category><![CDATA[Places API]]></category>

		<guid isPermaLink="false">http://blog.newsplore.com/?p=1658</guid>
		<description><![CDATA[&#160;&#160; Location Based Services are all the rage these days. The space is still being defined and the players are trying to differentiate their service offerings in order to attract the critical mass of developers. In this post I&#8217;ll draw a side-by-side comparison of the main features provided by the major Places API providers today. [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="padding-right:0;margin-top:3px"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.newsplore.com%2F2011%2F03%2F23%2Fa-comparison-of-places-apis"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.newsplore.com%2F2011%2F03%2F23%2Fa-comparison-of-places-apis" height="61" width="51" /></a></div><table>
<tr>
<td><img src='/wp-content/uploads/2011/03/pinsonmap.jpg' /></td>
<td>&nbsp;&nbsp;</td>
<td valign='top' align='justify'>Location Based Services are all the rage these days. The space is still being defined and the players are trying to differentiate their service offerings in order to attract the critical mass of developers. In this post I&#8217;ll draw a side-by-side comparison of the main features provided by the major Places API providers today. While I have no hard numbers to back-up the &#8220;major provider&#8221; claim, I&#8217;ll simply go for the web</td>
</tr>
<tr>
<td colspan='3'>companies I would look for when building an application around Location services.</td>
</table>
<p>Here are my candidates ordered by their first API release date:</p>
<table style="text-align: center" border="1" align="center">
<tbody>
<tr>
<td style="width: 100px" align="center"><b>Provider</b></td>
<td style="width: 140px" align="center"><b>Name</b></td>
<td style="width: 200px" align="center"><b>API Link</b></td>
<td style="width: 100px" align="center"><b>First Released</b></td>
</tr>
<tr>
<td>Yahoo</td>
<td>Yahoo GeoPlanet API</td>
<td><a href="http://developer.yahoo.com/geo/geoplanet/">Yahoo! GeoPlanet™</a></td>
<td>May 2009</td>
</tr>
<tr>
<td>Foursquare</td>
<td>Foursquare API</td>
<td><a href="http://developer.foursquare.com/docs/">Foursquare APIv2</a></td>
<td>Nov. 2009</td>
</tr>
<tr>
<td>Twitter</td>
<td>Twitter Places API</td>
<td>Geo methods in <a href="http://apiwiki.twitter.com/w/page/22554679/Twitter-API-Documentation">Twitter API</a></td>
<td>Jun. 2010</td>
</tr>
<tr>
<td>Facebook</td>
<td>Facebook Places API</td>
<td>Scattered under the <a href="http://developers.facebook.com/docs/reference/api/">Graph API</a></td>
<td>Aug. 2010</td>
</tr>
<tr>
<td>Google</td>
<td>Google Places API</td>
<td><a href="http://code.google.com/apis/maps/documentation/places/">Google Places API</a></td>
<td>Nov. 2010</td>
</tr>
</tbody>
</table>
<p>The features of all these APIs are designed primarily to support (and promote) the business use cases of each respective competitor. One notable exception is Yahoo&#8217;s GeoPlanet API which advertises itself as being a general purpose API for referencing places. </p>
<p>I won&#8217;t try to identify any &#8220;best&#8221; API in the end. This post is meant to allow the reader to make an informed decision on which API(s) to use.</p>
<p><span id="more-1658"></span>Since there can be only one true collection of physical places (we&#8217;re not dealing with quantum realities fortunately) and lacking a common industry effort towards harmonization, the default behavior is to compete to win or dominate the space. One notable mention, Foursquare is now trying to aggregate the various place identifiers referring to the same physical place through <a href="http://developer.foursquare.com/venues/">Venues Project</a>. Others will follow suit.</p>
<p>A comparison of features available in each API:</p>
<table style="text-align: center" border="1" align="center">
<tbody>
<tr>
<td style="width: 100px" align="center"><b>Provider</b></td>
<td style="width: 140px" align="center"><b>Place Identifier</b></td>
<td style="width: 200px" align="center"><b>Place Data Structure</b></td>
<td style="width: 80px" align="center"><b>Checkin</b></td>
<td style="width: 100px" align="center"><b>Create Place</b></td>
<td style="width: 80px" align="center"><b>Geocoding</b></td>
</tr>
<tr>
<td>Yahoo</td>
<td><a href="http://developer.yahoo.com/geo/geoplanet/guide/concepts.html#woeids">WOE ID</a></td>
<td><a href="http://developer.yahoo.com/geo/geoplanet/guide/api_docs.html#response_formats">XML, JSON, GeoJSON</a></td>
<td>No</td>
<td>No</td>
<td><a href="http://developer.yahoo.com/geo/placefinder/">Yes</a></td>
</tr>
<tr>
<td>Foursquare</td>
<td>Venue ID</td>
<td><a href="http://developer.foursquare.com/docs/responses/venue.html">JSON, JSONP</a></td>
<td><a href="http://developer.foursquare.com/docs/checkins/add.html">Yes</a></td>
<td><a href="http://developer.foursquare.com/docs/venues/add.html">Yes</a></td>
<td>No</td>
</tr>
<tr>
<td>Twitter</td>
<td>Geo ID</td>
<td><a href="http://apiwiki.twitter.com/w/page/23798004/Twitter-REST-API-Method:-GET-geo-ID">JSON</a></td>
<td>No</td>
<td>No</td>
<td><a href="http://apiwiki.twitter.com/w/page/23796618/Twitter-REST-API-Method:-GET-geo-reverse_geocode">Yes</a></td>
</tr>
<tr>
<td>Facebook</td>
<td>Numeric id</td>
<td>JSON</td>
<td><a href="http://developers.facebook.com/docs/reference/api/checkin/">Yes</a></td>
<td>No</td>
<td>No</td>
</tr>
<tr>
<td>Google</td>
<td>Place id</td>
<td><a href="http://code.google.com/apis/maps/documentation/places/#PlaceDetailsResponses">JSON, XML</a></td>
<td><a href="http://code.google.com/apis/maps/documentation/places/#PlaceCheckins">Yes</a></td>
<td>No</td>
<td><a href="http://code.google.com/apis/maps/documentation/geocoding/">Yes</a></td>
</tr>
</tbody>
</table>
<p>Discovering places is an important feature and all competitors offer it:</p>
<table style="text-align: center" border="1" align="center">
<tbody>
<tr>
<td style="width: 100px" align="center"><b>Provider</b></td>
<td style="width: 200px" align="center"><b>Nearby</b></td>
<td style="width: 140px" align="center"><b>Textual Search</b></td>
<td style="width: 80px" align="center"><b>Popular Places</b></td>
</tr>
<tr>
<td>Yahoo</td>
<td><a href="http://developer.yahoo.com/geo/geoplanet/guide/api-reference.html#api-places">Yes</a></td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>Foursquare</td>
<td><a href="http://developer.foursquare.com/docs/venues/search.html">Mandatory</a></td>
<td>Yes</td>
<td><a href="http://developer.foursquare.com/docs/venues/trending.html">Trending</a></td>
</tr>
<tr>
<td>Twitter</td>
<td><a href="http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-GET-geo-nearby_places">Yes</a></td>
<td>No</td>
<td><a href="http://apiwiki.twitter.com/w/page/22554753/Twitter-REST-API-Method:-trends-location">Per topic</a></td>
</tr>
<tr>
<td>Facebook</td>
<td>Mandatory</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>Google</td>
<td><a href="http://code.google.com/apis/maps/documentation/places/#PlaceSearchRequests">Mandatory</a></td>
<td>Yes</td>
<td>No</td>
</tr>
</tbody>
</table>
<p>What kind of data is returned when fetching a place?</p>
<table style="text-align: center" border="1" align="center">
<tbody>
<tr>
<td style="width: 100px" align="center"><b>Provider</b></td>
<td style="width: 140px" align="center"><b>Place contents</b></td>
</tr>
<tr>
<td>Yahoo</td>
<td>Core only*</td>
</tr>
<tr>
<td>Foursquare</td>
<td>Contact info, specials here &amp; nearby,<br />
who&#8217;s here now, tips,<br />
photos, verified, who&#8217;s mayor</td>
</tr>
<tr>
<td>Twitter</td>
<td>Core only*</td>
</tr>
<tr>
<td>Facebook</td>
<td>Core only*</td>
</tr>
<tr>
<td>Google</td>
<td>Core, icon, rating,<br />
Google place details page URL</td>
</tr>
</tbody>
</table>
<p>*Core Place data is represented differently by each provider, see individual documentation for more details.</p>
<p>What are the access restrictions when using the APIs?</p>
<table style="text-align: center" border="1" align="center">
<tbody>
<tr>
<td style="width: 100px" align="center"><b>Provider</b></td>
<td style="width: 140px" align="center"><b>Authentication scheme</b></td>
<td style="width: 140px" align="center"><b>Terms of Use</b></td>
<td style="width: 140px" align="center"><b>Usage Limits</b></td>
</tr>
<tr>
<td>Yahoo</td>
<td>Open, requires appId</td>
<td><a href="http://info.yahoo.com/legal/us/yahoo/api/api-2140.html">TOS</a></td>
<td>50k queries/day</td>
</tr>
<tr>
<td>Foursquare</td>
<td><a href="http://developer.foursquare.com/docs/oauth.html">OAuth 2.0</a></td>
<td><a href="http://foursquare.com/legal/api">API Terms of Service</a></td>
<td><a href="http://groups.google.com/group/foursquare-api/browse_thread/thread/c7d2d0e20ae093e2/ba157981fb4f3d77?lnk=gst&amp;q=limits#ba157981fb4f3d77">200</a> requests/hour/method</td>
</tr>
<tr>
<td>Twitter</td>
<td><a href="http://apiwiki.twitter.com/w/page/22554643/Authentication">OAuth</a></td>
<td><a href="http://dev.twitter.com/pages/api_terms">TOS</a></td>
<td><a href="http://dev.twitter.com/pages/rate-limiting">350</a> requests/hour</td>
</tr>
<tr>
<td>Facebook</td>
<td><a href="http://developers.facebook.com/docs/authentication/">OAuth 2.0</a></td>
<td><a href="http://developers.facebook.com/policy/">FB Platform Policy</a></td>
<td>N/A</td>
</tr>
<tr>
<td>Google</td>
<td><a href="http://code.google.com/apis/maps/documentation/webservices/index.html#URLSigning">URL Signing</a></td>
<td><a href="http://code.google.com/apis/maps/documentation/places/#Requirements">Acceptable use Requirements</a></td>
<td><a href="http://code.google.com/apis/maps/documentation/places/#Limits">Unspecified yet</a></td>
</tr>
</tbody>
</table>
<p>This concludes the comparison galore.</p>
<p>The only offering that felt &#8220;general purpose&#8221; was Yahoo&#8217;s. The API is designed to provide generic access to the place information while not tying to any specific Yahoo data. All of the other offerings are built around specific features provided by the vendor (although the core place information is neutral in each case).</p>
<p>An interesting comparison would be showing the POI coverage for each API provider but this data is unavailable.</p>
<p>I would have liked to add a few more comparisons like number of apps using each API, daily usage. This data is also not public (or at least I couldn&#8217;t find it).</p>
<p><i>Flickr image courtesy mil8</i></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.newsplore.com/2011/03/23/a-comparison-of-places-apis/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Towards An Open Database of Places: Location Autodiscovery</title>
		<link>http://blog.newsplore.com/2010/08/20/location-audiscovery</link>
		<comments>http://blog.newsplore.com/2010/08/20/location-audiscovery#comments</comments>
		<pubDate>Fri, 20 Aug 2010 09:39:29 +0000</pubDate>
		<dc:creator>Florin</dc:creator>
				<category><![CDATA[software]]></category>

		<guid isPermaLink="false">http://blog.newsplore.com/?p=1556</guid>
		<description><![CDATA[A short while back I read a challenging article titled t’s Time For An Open Database Of Places. There, Erich Schonfeld notes: A long list of companies including Twitter, Google, Foursquare, Gowalla, SimpleGeo, Loopt, and Citysearch are far along in creating separate databases of places mapped to their geo-coordinates. These efforts at creating an underlying [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="padding-right:0;margin-top:3px"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.newsplore.com%2F2010%2F08%2F20%2Flocation-audiscovery"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.newsplore.com%2F2010%2F08%2F20%2Flocation-audiscovery" height="61" width="51" /></a></div><table>
<tr>
<td><a href="http://blog.newsplore.com/wp-content/uploads/2010/08/68012770_7701314a08_m.jpg"><img src="http://blog.newsplore.com/wp-content/uploads/2010/08/68012770_7701314a08_m.jpg" alt="" width="240" height="180" class="alignnone size-full wp-image-1646" /></a></td>
<td>A short while back I read a challenging article titled <a href='http://techcrunch.com/2010/04/17/open-database-places/'>t’s Time For An Open Database Of Places</a>. There, Erich Schonfeld notes:</p>
<pre>
A long list of companies including Twitter, Google,
Foursquare, Gowalla, SimpleGeo, Loopt, and
Citysearch are far along in creating separate
databases of places mapped to their
geo-coordinates.
</pre>
</td>
</tr>
</table>
<pre>
 These efforts at creating an underlying database of places are duplicative, and any
competitive advantage any single company gets from being more comprehensive than
the rest will be short-lived at best. It is time for an open database of places which all
companies and developers can both contribute to and borrow from.
</pre>
<p>I agree that there is duplication of effort but this is what happens with many competitive technologies (look at now many online maps are available today). Each company tries to add a competitive advantage to its offering while providing the same core functionality as the competition.<br />
<i>Update: I started this post back in April and a lot of developments recently only enforce: <a href='http://techcrunch.com/2010/08/19/bye-bye-thomas-guides/'>this point</a></i>. (Check <a href='http://techcrunch.com/2010/08/18/facebook-wants-advertisers-to-help-build-out-its-directory-of-places/'>Facebook Places</a> and <a href='http://www.google.com/local/add/analyticsSplashPage'>Google Places</a> for more info).</p>
<p>I like the idea of an open database of places. Any company could build value-added services on top of it and sell them while they are not concerned about issues that come with building and maintaining such database like geo-location/address accuracy and duplicate place resolution to name just a few. Techcrunch&#8217;s Schonfeld adds another issue: who can a place and who should be in control of it, suggesting that anybody can update the database and &#8220;the best data should prevail&#8221;. This is hard and suggests a wiki-like approach for better or worse.<br />
I&#8217;m not a fan of centralizing such database. Since there are such great market forces at play, it may become a playground for fights (my data is better than yours), a committee will attempt to regulate it just to push it into oblivion while everybody will get their toys and go build their own database.</p>
<p>I have a different idea (and it&#8217;s not new either).</p>
<p>Businesses have a great deal of interest in such database. It puts them on the map. They don&#8217;t particularly care who is using their place as long as the data about their business is correct and their customers easily reach their venue. The experience with using a mobile routing software to get to a place in real world is the equivalent of not waiting more than <a href='http://www.akamai.com/html/about/press/releases/2006/press_110606.html'>four seconds</a> for a webpage to load. It just has to route the customer precisely to a location.</p>
<p>Why not letting the business to own their own geo data? All it takes is for them to have a website and add a bit of information to it to allow for auto-discovery; it&#8217;s called <a href='http://en.wikipedia.org/wiki/Geotagging'>geotagging</a>. It&#8217;s the <a href='http://mattgriffith.net/2002/05/29.html#a57'>same idea</a> that Matt Griffith had back in 2002 that allows <a href='http://www.rssboard.org/rss-autodiscovery'>RSS feed autodiscovery</a> applied to geo. The real win is for small businesses that adopt geotagging. All they need to do is add a small bit of metadata on their homepage and let web indexers do the job of collecting this data. Oh, and it&#8217;s free.<br />
This brings a double win: companies in the mapping business access accurate geo information about businesses. The business themselves are happy that their customers can precisely find their physical location by means of  address and/or geo-coordinates. Moreover, the accuracy of the data is maintained by the businesses since they want their customers to find them even when they move. A Places database that aggregates this type of data can mark these places as &#8220;verified&#8221; since they come directly from merchants. It even provides more accurate means of building forward and reverse geocoding tools.<br />
Going forward with this model, the competition will shift their efforts from building a database of places to adding value to a (more or less) common Places database like local promotions and building great mapping products to allow us, the customers to find them.</p>
<p>The hard part is promoting this model. If say, half of the brick and mortar small businesses with a web presence embed geo metadata on their website, then the big players take notice. How to get there is the real challenge.</p>
<p><i>Image via Flickr/<a href='http://www.flickr.com/photos/bryankennedy/68012770/'>bryankennedy</a></i></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.newsplore.com/2010/08/20/location-audiscovery/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RESTful error handling with Tomcat and SpringMVC 3.x</title>
		<link>http://blog.newsplore.com/2010/08/04/restful-error-handling-with-tomcat-springmvc</link>
		<comments>http://blog.newsplore.com/2010/08/04/restful-error-handling-with-tomcat-springmvc#comments</comments>
		<pubDate>Wed, 04 Aug 2010 09:16:06 +0000</pubDate>
		<dc:creator>Florin</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[Java SpringMVC REST Error Handling]]></category>

		<guid isPermaLink="false">http://blog.newsplore.com/?p=1602</guid>
		<description><![CDATA[Handling errors in a REST way is seemingly simple enough: upon requesting a resource, when an error occurs, a proper status code and a body that contains a parseable message and using the content-type of the request should be returned. The default error pages in Tomcat are ugly. Not only they expose too much of [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="padding-right:0;margin-top:3px"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.newsplore.com%2F2010%2F08%2F04%2Frestful-error-handling-with-tomcat-springmvc"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.newsplore.com%2F2010%2F08%2F04%2Frestful-error-handling-with-tomcat-springmvc" height="61" width="51" /></a></div><p>Handling errors in a REST way is seemingly simple enough: upon requesting a resource, when an error occurs, a proper status code and a body that contains a parseable message and using the content-type of the request should be returned.<br />
The default error pages in Tomcat are ugly. Not only they expose too much of the server internals, they are only HTML formatted and making them a poor choice if a RESTful web service is deployed in that Tomcat container. Substituting them to simple static pages is still no enough since I want a dynamic response containing error information.</p>
<p>Here&#8217;s how to do it in 3 simple steps:</p>
<p><span id="more-1602"></span></p>
<p><i>Step 1</i><br />
In web.xml </p>
<pre>
   &lt;servlet-mapping&gt;
      &lt;servlet-name&gt;jsp&lt;/servlet-name&gt;
      &lt;url-pattern&gt;/error.jsp&lt;url-pattern&gt;
   &lt;/servlet-mapping&gt;
   &lt;!-- other servlet mappings --&amp;&amp;gt&amp;

  &lt;error-page&gt;
    &lt;error-code&gt;404&lt;/error-code&gt;
    &lt;location&gt;/error.jsp&lt;/location&gt;
  &lt;/error-page&gt;
  &lt;error-page&gt;
    &lt;error-code&gt;400&lt;/error-code&gt;
    &lt;location&gt;/error.jsp&lt;/location&gt;
  &lt;/error-page&gt;
...
  &lt;error-page&gt;
    &lt;exception-type&gt;java.lang.Throwable&lt;/exception-type&gt;
    &lt;location&gt;/error.jsp&lt;/location&gt;
  &lt;/error-page&gt;
</pre>
<p>The servlet called <b>jsp</b> comes out-of the box with the Tomcat container and is the one responsible for processing JSPs . Make sure this mapping comes first, especially if you have a catch-all url-pattern that should map all other URLs to your webapp.</p>
<p><i>Step 2</i><br />
Create a file called errors.jsp in the root of your web application:</p>
<pre>
&lt;%@ page contentType="application/json" pageEncoding="UTF-8"%&gt;
{
   status:&lt;%=request.getAttribute("javax.servlet.error.status_code") %&gt;,
   reason:&lt;%=request.getAttribute("javax.servlet.error.message") %&gt;
}
</pre>
<p><i>Step 3</i><br />
Hook the exception handling using @ExceptionHandler:</p>
<pre>
@Controller
public class SomeController {
...

@ExceptionHandler(BusinessException.class, ValidationException.class, ...)
public void handleApplicationExceptions(Throwable exception, HttpServletResponse response) {
   String formattedErrorForFrontEnd = formatErrMessage(exception);
   if(exception instanceof BusinessException) {
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
formattedErrorForFrontEnd);
   } else if (exception instanceof ValidationException) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, formattedErrorForFrontEnd);
   }
   ...
}

//other @ExceptionHandlers skipped

   private String formatErrMessage(Throwable exception) {
      //skipped
   }
}
</pre>
<p>I used @ExceptionHandler to map between application exceptions and error codes. You can apply message formatting as well if the default messages are not sufficient. Also, consider having an @ExceptionHandler(Throwable.class) for the &#8220;all other exceptions&#8221; case.</p>
<p>As you can see, there is no need to write another Spring Controller that handles exceptional paths. The error-page mappings in web.xml, a 2 line JSP and the standard @ExceptionHandler combination was sufficient.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.newsplore.com/2010/08/04/restful-error-handling-with-tomcat-springmvc/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Building a content aggregation service with node.js</title>
		<link>http://blog.newsplore.com/2010/06/27/building-a-content-aggregation-service-with-node-js</link>
		<comments>http://blog.newsplore.com/2010/06/27/building-a-content-aggregation-service-with-node-js#comments</comments>
		<pubDate>Sun, 27 Jun 2010 21:58:25 +0000</pubDate>
		<dc:creator>Florin</dc:creator>
				<category><![CDATA[software]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[node.js]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://blog.newsplore.com/?p=1580</guid>
		<description><![CDATA[Fetching, aggregating and transforming data for delivery is a seemingly complex task. Imagine a service that serves aggregated search results from Twitter, Google and Bing where the response has to be tailored for mobile and web. One has to fetch data from different sources, parse and compose the results then transform them into the right [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="padding-right:0;margin-top:3px"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.newsplore.com%2F2010%2F06%2F27%2Fbuilding-a-content-aggregation-service-with-node-js"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.newsplore.com%2F2010%2F06%2F27%2Fbuilding-a-content-aggregation-service-with-node-js" height="61" width="51" /></a></div><p>Fetching, aggregating and transforming data for delivery is a seemingly complex task. Imagine a service that serves aggregated search results from Twitter, Google and Bing where the response has to be tailored for mobile and web. One has to fetch data from different sources, parse and compose the results then transform them into the right markup for delivery to a specific client platform.<br />
To cook this I&#8217;ll need:<br />
- a web server<br />
- a nice way to aggregate web service responses (<a href='http://en.wikipedia.org/wiki/HTTP_pipelining'>pipelining</a> would be nice)<br />
- a component to transform the raw aggregated representation into a tailored client response.</p>
<p>I could take a stab at it and use Apache/Tomcat, Java (using Apache HttpClient 4.0), a servlet dispatcher (Spring WebMVC) and Velocity templating but it sounds too complex.<br />
<br />
Enter <a href='http://nodejs.org'>Node.js</a>. It&#8217;s an event-based web server built on Google&#8217;s V8 engine. It&#8217;s fast and it&#8217;s scalable and you develop on it using the familiar Javascript.<br />
While Nodejs is still new, the community has built a rich ecosystem of extensions (<a href='http://wiki.github.com/ry/node/modules'>modules</a>) that greatly ease the pain of using it.  If you&#8217;re unfamiliar with the technology, check-out the Hello World example, it should get you started.<br />
Back to the task at hand, here are the modules I&#8217;ll need:<br />
- <a href='http://github.com/danwrong/restler'>Restler</a> to get me data.<br />
- <a href='http://github.com/caolan/async'>async</a> to allow parallelizing requests for effective data fetching.<br />
- <a href='http://howtonode.org/haml-for-javascript'>Haml-js</a> for view generation</p>
<p><span id="more-1580"></span><br />
To restate the requirement, we want to aggregate results from Google and Twitter using any arbitrary search predicate.<br />
First we need node.js itself:</p>
<pre>
git clone http://github.com/ry/node/tree/master
./configure
make
sudo make install
</pre>
<p>Let&#8217;s bring the necessary modules. Create a project directory then fetch them in it:</p>
<pre>
git clone  http://github.com/caolan/async.git
git clone http://github.com/danwrong/restler.git
git clone http://github.com/creationix/haml-js.git
</pre>
<p>Most of the action take place in one file that fires the webserver and contains all the event logic. My small little server is called servus.js so I&#8217;ll call the file just that.</p>
<p><i>Update Jun/28: </i>Servus now lives in github, grab it <a href='http://github.com/florind/servus'>here</a></p>
<p>First thing, import all the modules, assuming that all of them are in the root of the project directory and create the basic port listener (all code in servus.js):</p>
<pre>
var sys = require('sys'),
  http = require('http'),
  rest = require('./restler/lib/restler'),
  async = require('./async/lib/async'),
  haml = require('./haml-js/lib/haml');
  url = require('url'),
  fs = require('fs');

http.createServer(function (req, res) {
    process.addListener('uncaughtException', function (err) {
      sys.puts('Caught exception: ' + err);
      res.writeHead(500, 'text/plain');
      res.end('error!');
    });

   res.writeHead(200, {'Content-Type': 'text/plain'});
   res.end('Servus\n');
}).listen(8124, "127.0.0.1");
sys.puts('Server running at http://127.0.0.1:8124/');
</pre>
<p>Listening for &#8216;uncaughtException&#8217; events ensures that the server keeps running when an exception occurs. Run this with <i>node servus.js</i> and you should see the server responding with &#8216;Servus&#8217; when browsing to http://localhost.</p>
<p>Let&#8217;s add some real code. First, we define the request URLs for Twitter and Google. Next,  parse the URL and extract the query predicate. Servus will respond to /aggregate?q= requests and querying both search services using async. Replace res.writeHead and res.end lines with:</p>
<pre>
    var serviceUrls = {};
    serviceUrls.twit = 'http://search.twitter.com/search.json?q=';
    serviceUrls.goo = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&amp;q=';
    var urlParsed = url.parse(req.url, true);
    var path = urlParsed.pathname;

    switch(path) {
      case '/aggregate':
        //extract search predicate
        var query = urlParsed.query;
        if(query != undefined) {
          predicate = query.q;
        } else {
          res.writeHead(400);
          res.end('Query expected. Use q=... in the URL');
          return;
        }
        async.parallel([
          function(callback) {
            callRestService(serviceUrls['goo'] + predicate, 'goo', callback);
          },
          function(callback) {
            callRestService(serviceUrls['twit'] + predicate, 'twit', callback);
          }
        ],
        //callback
        function (err, results) {
             //use the results argument and a haml template to form the view.
        }
      );
      break;
</pre>
<p>Through the async module, both GET requests are fetched in parallel. The <i>callback</i> function is called after all functions in the first argument async.parallel have been completed; the &#8216;results&#8217; argument in the callback function accumulates the search results in an array. The function &#8216;callRestService&#8217; gets the JSON results and parses them in hashes of format {url: &#8230;, text: &#8230;}. Let&#8217;s implement it:</p>
<pre>
    function callRestService(url, serviceName, callback) {
        request = rest.get(url);
        request.addListener('success', function(data) {
            searchResults = [];
            if(serviceName == 'goo') {
              dataJson = JSON.parse(data).responseData.results;
              for(sr in dataJson) {
                searchResult = {}
                searchResult.url = dataJson[sr].url;
                searchResult.text = dataJson[sr].title;
                searchResults.push(searchResult);
              }
            } else if(serviceName == 'twit') {
              dataJson = data.results;
              for(sr in dataJson) {
                searchResult = {}
                searchResult.url = 'http://twitter.com/' + dataJson[sr].from_user +
 '/status/' + dataJson[sr].id;
                searchResult.text = dataJson[sr].text;
                searchResults.push(searchResult);
              }
            }
          callback(null, searchResults);
        });
        request.addListener('error', function(data) {
          sys.puts('Error fetching [' + url + ']. Body:\n' + data);
          callback(null, ' ');
        });
    }
</pre>
<p>The callback function in async.parallel takes the search results and will a use haml template to produce the view for web serving. Here&#8217;s the template (search-res.haml):</p>
<pre>
%h1 Search results
  :if items.length === 0
    %p There are no search results
  :if items.length &gt; 0
    %table
      :each sr in items
        %tr
          %td %a{href: sr.url}&amp;= sr.text
</pre>
<p>We&#8217;ll load this template and use it subsequently in the callback function:</p>
<pre>
    //load template; this goes before http.createServer
    var searchResHamlTemplate;
    fs.readFile('./search-res.haml', function(e, c) {
        searchResHamlTemplate = c.toString();
      });
</pre>
<p>The callback function above is implemented like this:</p>
<pre>
        //callback
        function (err, results) {
          //results accumulated two arrays of search results,
          //for google and twitter respectively.

          res.writeHead(200, {'Content-Type': 'text/html'});
          var searchItems = [];
          for(i=0;i&lt;results.length;i++) {
            for(sr in results[i]) {
              searchItems.push(results[i][sr]);
            }
          }
          res.end(haml.render(searchResHamlTemplate, {locals: {items: searchItems}}));
        }
</pre>
<p>Done. You can grab the complete code here: <a href='http://blog.newsplore.com/wp-content/uploads/2010/06/servus.js'>servus.js</a>. The final version contains a few more bits to be able to properly respond to GET queries. Querying the server using http://localhost:8124/aggregate?q=worldcup will render a few google results on top followed by all twitter search results.</p>
<p><b>Adding a Service Level Agreement guarantee</b><br />
What if we want to add SLA (service level agreement) to our little server? Some web service clients require that servers respond within a guaranteed time. Turns out it&#8217;s not hard at all. We only have to add one more function in the parallel.async call that is called after the preset timeout using setTimeout:</p>
<pre>
    var timeoutReached = false;
...
        async.parallel([
          function(callback) {
            callRestService(serviceUrls['goo'] + predicate, 'goo', callback);
          },
          function(callback) {
            callRestService(serviceUrls['twit'] + predicate, 'twit', callback);
          },
          function(callback) {
            setTimeout(function() {
              if(!timeoutReached) {
                //serve search results if any
                serveContent(partialResults);
                sys.puts("Timeout reached");
              }
            }, 200);
          }
        ]);
</pre>
<p>partialResults is an array where search results are accumulated as they come in. If this array size becomes 2 then we know that the fetch/parse has completed and the result can be served to the view:</p>
<pre>

    function callRestService(url, serviceName, callback) {
        request = rest.get(url);
        request.addListener('success', function(data) {

...same as before...

           partialResults.push(searchResults);
           if(partialResults.length ==  2 &amp;&amp; !timeoutReached) {
             sys.puts("Timeout not reached");
             serveContent(partialResults);
           }
        });

    function serveContent(results) {

...same as before...

      timeoutReached = true;  //prevent further search results to be processed
    }
</pre>
<p>Lastly, timeoutReached flag is turned off in serveContent to prevent further results to be processed.</p>
<p><del datetime="2010-06-28T15:35:31+00:00">I&#8217;ve attached the final version of servus.js with sla: <a href='http://blog.newsplore.com/wp-content/uploads/2010/06/servus-sla.js'>servus-sla.js</a>.</del> The code is available now in a github project called <a href='http://github.com/florind/servus'>servus</a>. The sla timeout is specified as an argument when starting nodejs. If none is specified, the default is 2 seconds.</p>
<p>If you&#8217;re behind a corporate proxy, use proxychains. You can find more details about this issue <a href='http://groups.google.com/group/nodejs/browse_thread/thread/0d5aadbcaa00c3f7'>here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.newsplore.com/2010/06/27/building-a-content-aggregation-service-with-node-js/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Using Spring 3.0 MVC for RESTful web services (rebuttal)</title>
		<link>http://blog.newsplore.com/2010/02/23/spring-mvc-3-0-rest-rebuttal</link>
		<comments>http://blog.newsplore.com/2010/02/23/spring-mvc-3-0-rest-rebuttal#comments</comments>
		<pubDate>Tue, 23 Feb 2010 22:18:53 +0000</pubDate>
		<dc:creator>Florin</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[SpringMVC]]></category>

		<guid isPermaLink="false">http://blog.newsplore.com/?p=1486</guid>
		<description><![CDATA[Update Mar.04 Thanks to @ewolff some of the points described below are now official feature requests. One (SPR-6928) is actually scheduled in Spring 3.1 (cool!). I&#8217;ve updated the post and added all open tickets. Please vote! This post is somewhat a response to InfoQ&#8217;s Comparison of Spring MVC and JAX-RS. Recently I have completed a [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="padding-right:0;margin-top:3px"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.newsplore.com%2F2010%2F02%2F23%2Fspring-mvc-3-0-rest-rebuttal"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.newsplore.com%2F2010%2F02%2F23%2Fspring-mvc-3-0-rest-rebuttal" height="61" width="51" /></a></div><p><i>Update Mar.04</i> Thanks to @ewolff some of the points described below are now official feature requests. One (<a href='http://jira.springframework.org/browse/SPR-6928'>SPR-6928</a>) is actually scheduled in Spring 3.1 (cool!). I&#8217;ve updated the post and added all open tickets. Please vote!</i></p>
<p>This post is somewhat a response to InfoQ&#8217;s <a href='http://www.infoq.com/articles/springmvc_jsx-rs'>Comparison of Spring MVC and JAX-RS</a>.<br />
Recently I have completed a migration from a JAX-RS implementation of a web service to Spring 3.0 MVC annotation-based <i>@Controllers</i>. The aforementioned post on InfoQ was published a few days after my migration so I&#8217;m dumping below the list of problems I had, along with solutions. </p>
<p>Full list of issues:</p>
<ul>
<li> <a href='#relpaths'>Same relative paths in multiple controllers not supported</a>
<li> <a href='#exchandling'>@ExceptionHandler is controller-centric</a>
<li> <a href='#views'>Standard content negotiation can&#8217;t respond with a fixed response type</a>
<li> <a href='#jsr303'>JSR 303 bean validation not applied in @Controllers</a>
<li> <a href='#respfmt'>Formatting responses (i.e. Date) not working when using Spring formatter annotations</a>
</ul>
<p><a name='relpaths'></a><br />
<b>Same relative paths in multiple @Controllers not supported</b><br />
Consider two Controllers where I use a versioned URL and a web.xml file that uses two URL mappings:</p>
<pre>
@Controller
public class AdminController {
   @RequestMapping("/v1/{userId}")
   public SomeResponse showUserDetails(String userId) {
      ...
   }
}

@Controller
public class UserController {
   @RequestMapping("/v1/{userId}")
   public SomeOtherResponse showUserStreamtring userId) {
      ...
   }
}
In web.xml:
	&lt;servlet-mapping&gt;
	  &lt;servlet-name&gt;public-api&lt;/servlet-name&gt;
	  &lt;url-pattern&gt;/public&lt;/url-pattern&gt;
	&lt;/servlet-mapping&gt;
	&lt;servlet-mapping&gt;
	  &lt;servlet-name&gt;admin-api&lt;/servlet-name&gt;
	  &lt;url-pattern&gt;/admin&lt;/url-pattern&gt;
	&lt;/servlet-mapping&gt;
</pre>
<p><span id="more-1486"></span><br />
Here I want to implement handling for <i>/admin/v1/{userId}</i> as well as <i>/user/v1/{userId}</i>. Each controller serves a different purpose (admin and public) and I want to keep the servlet application contexts separate for each servlet mapping (for instance add authentication and different view resolvers to all /admin/* URLs).<br />
Deploying this configuration barfs the following exception:</p>
<pre>
java.lang.IllegalStateException: Cannot map handler [UserController] to URL path
[/v1/{userId}]: There is already handler [com.test.controller. UserController@6b177115]
mapped.
</pre>
<p>I would like Spring MVC to account for web.xml servlet mappings before deciding that two identical @RequestMappings in different controllers refer to the same URI. My solution was to have all @RequestMappings specifying the full path and resorting to a custom <a href='#views'>view</a> to work around this issue).</p>
<p><a name='exchandling'></a><br />
<b>@ExceptionHandler is controller-centric</b><br />
RESTful web services respond with the usual HTTP responses (200s, 400s, 500s, etc.). These responses are being mapped from application exceptions and it only makes sense to specify the same @ExceptionHandler for all @Controllers since most (if not all) exceptions handled by them are for the same business domain. Currently SpringMVC only supports declaring and @ExceptionHander per controller and not globally per webapp. This forces the implementors to extend their @Controller classes from a common one where the @ExceptionHandler is specified or, to use composition and delegate exception handling to one service which leads to duplication. Both are ugly. There are several ways to deal with exceptions (check <a href='http://jira.springframework.org/browse/SPR-5622?focusedCommentId=43377&amp;page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#action_43377'>SPR-5622</a>; please guys, add this to the main Spring documentation) but ideally I&#8217;d like to see a global scoped handler like @ExceptionHandler(scope=APPLICATION) where I can remap once framework exceptions to more suitable ones that translate into proper error codes (like working around <a href='http://jira.springframework.org/browse/SPR-5622'>SPR-5622</a> like issues).</p>
<p><a name='views'></a><br />
<b>Standard content negotiation can&#8217;t respond with a fixed response type (<a href='http://jira.springframework.org/browse/SPR-6937'>SPR-6937</a>)</b><br />
Here&#8217;s a simple requirement: Implement an RSS feed that serves a user&#8217;s activity stream.<br />
Here&#8217;s another requirement (make that best practice): </p>
<pre>Service methods should have as arguments primitives, wrappers or other POJOs and
 respond with void, primitives, wrappers or other POJOs.</pre>
<p>I want testability, readability and portability for service classes and using framework objects for arguments/return objects adds unacceptable clutter.<br />
As such, no framework objects are allowed as arguments or return types in a @Controller and in this case I don&#8217;t want to work with <a href='http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/servlet/ModelAndView.html'>ModelAndView</a>s just to be able to select the desired View.<br />
Since this new requirement (add RSS view) belongs to the user domain, I want to add a method in the UserController class that returns a POJO which should be always unmarshalled into RSS regardless of request content type (there goes <a href='http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.html'>ContentNegotiationViewResolver</a>). The same controller has other methods returning POJO view objects that I want marshalled into JSON or plain text response body and an HTTP response status. This is already available in RESTEasy via the elegant <a href='http://jboss.org/file-access/default/members/resteasy/freezone/docs/1.0.1.GA/javadocs/javax/ws/rs/Produces.html'>Produces</a> annotation. The same RESTful controller should respond with different response types for different requests since I want to keep its domain centered around the user (and not response types).</p>
<pre>
...
public class UserController {
...
   @RequestHandler("/rss/{userId}")
   public SomePOJO getRssFeed(String userId) {
      ...
      //returns a POJO that should always be resolved by an RSS view
   }

   @RequestMapping("/activity/{userId}")
   public SomeOtherPOJO showUserStream(String userId) {
      ...
      //return POJO that should always be resolved by a JSON view
   }
...
}
</pre>
<p>It turns out this is not immediately possible. To my knowledge none of the included view resolvers provide a straight mapping between URLs and views so I had to write one that configures like this:</p>
<pre>
&lt;bean class="UrlToViewViewResolver"&gt;
   &lt;map name="urlToViewMap"&gt;
      &lt;property key="/user/rss/*" value="rssView"/&gt;
      &lt;property key="/user/activity/*" value="jsonView"/&gt;
      ...
   &lt;/map&gt;
&lt;/bean&gt;
</pre>
<p>The implementation (not included) is trivial and based on <a href='http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/util/AntPathMatcher.html'>AntPathMatcher</a>, a utility class readily available in Spring.</p>
<p><a name='jsr303'></a><br />
<b>JSR 303 bean validation not applied in @Controllers (<a href='http://jira.springframework.org/browse/SPR-6928'>SPR-6928</a>, scheduled for 3.1)</b><br />
On Springsource&#8217;s weblog there&#8217;s a nice tutorial on how to get validation and type conversion in Spring 3.0 <a href='http://blog.springsource.com/2009/11/17/spring-3-type-conversion-and-validation/'>here</a>. When it comes to validation though, Spring only supports it &#8220;after binding user input to it&#8221;. It is not possible to validate arguments and return types for a RESTful controller (no web forms or user input of any kind there). This means this won&#8217;t work out of the box:</p>
<pre>
   @RequestHandler("/admin/", method = RequestMethod.PUT )
   public void updateUser(@Valid User user) {
      ...
      //returns a POJO that should always be resolved by an RSS view
   }
</pre>
<p>since in a RESTful scenario the User object won&#8217;t be bound from a form but unmarshalled from XML/JSON/CSV or any other wire format.<br />
To enable validation for a RESTful controller I chose to use @Valid at the method level and add an around advice that intercepts all methods annotated as such then use a <a href='http://java.sun.com/javase/6/docs/api/javax/xml/validation/Validator.html'>Validator</a> to  validate arguments and return objects.</p>
<pre>
&lt;aop:config proxy-target-class="true"&gt;
	&lt;aop:pointcut id="validatableMethodExecution"
        expression="execution(* com.mycorp..*.*(..)) and @annotation(javax.validation.Valid)"/&gt;

	&lt;aop:aspect id="validateArgumentsAndReturnObject" ref="validatorAspect"&gt;
		&lt;aop:around pointcut-ref="validatableMethodExecution" method="validate"/&gt;
	&lt;/aop:aspect&gt;
&lt;/aop:config&gt;

public class ModelValidatorAspect {
	@Autowired
	private Validator validator;

    public Object validate(ProceedingJoinPoint pjp) throws Throwable {
        Set&lt;ConstraintViolation&gt; violations =new HashSet&lt;ConstraintViolation&gt;();
        for(Object obj : pjp.getArgs()) {
            if(obj != null) {
                violations.addAll(validator.validate(obj));
            }
        }
        if(!violations.isEmpty()) {
            throw new BadRequestException(composeErrorMessage(violations));
        }

        Object ret = pjp.proceed();

        //validate return object and throw exception if the validation fails.
        if(ret != null) {
            violations = validator.validate(ret);
        }
        if(!violations.isEmpty()) {
            throw new BusinessValidationException(violationsStr);
        }
   }
}
</pre>
<p>This could get more complex if you have deal with collections of validatable objects but it&#8217;s not hard to enhance the code to handle that.</p>
<p><a name='respfmt'></a><br />
<b>Formatting responses (i.e. Date) not working using Spring formatter annotations</b><br />
Spring comes with some niceties like @DateTimeFormat and @NumberFormat and naturally I want to rely on them by annotating the class attributes of return types used by @Controllers.<br />
That&#8217;s not quite working since the formatters work with form-backed model objects. However, if you use a <a>MappingJacksonJsonView</a> there is a way of formatting using Jackson&#8217;s own <a href='http://jackson.codehaus.org/1.2.1/javadoc/org/codehaus/jackson/map/annotate/JsonSerialize.html'>@JsonSerialize</a>.</p>
<p>Although at times it felt that the switch to SpringMVC was too much, the features that come with it (like abstracting web-related properties as annotations) will turn your RESTful controllers into annotated POJOs focused on the business domain which ultimately means maintainable code.</p>
<p><i>Update Mar.04</i> I left out several points about JSON marshalling that didn&#8217;t work as expected (Jackson marshaller is a handful).<br />
- One enhancement I suggested to ease the pain of configuring JSON marshalling is creating a namespace similar to oxm (<a href='http://jira.springframework.org/browse/SPR-6943'>SPR-6943</a>)<br />
- The second was to add <a href='http://jettison.codehaus.org/'>Jetisson</a> support (<a href='http://jira.springframework.org/browse/SPR-6938'>SPR-6938</a>) as an alternative to Jackson JSON marshaller.</p>
<p>I&#8217;m keen on your feedback regarding these issues so if you have better solutions please comment.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.newsplore.com/2010/02/23/spring-mvc-3-0-rest-rebuttal/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Unit testing with Commons HttpClient library</title>
		<link>http://blog.newsplore.com/2010/02/09/unit-testing-with-httpclient</link>
		<comments>http://blog.newsplore.com/2010/02/09/unit-testing-with-httpclient#comments</comments>
		<pubDate>Wed, 10 Feb 2010 00:31:25 +0000</pubDate>
		<dc:creator>Florin</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[mocks]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://blog.newsplore.com/?p=1442</guid>
		<description><![CDATA[I want to write testable code and occasionally I bump into frameworks that make it challenging to unit test. Ideally I want to inject a service stub into my code then control the stub&#8217;s behavior based on my testing needs. Commons Http Client from Jakarta facilitates integration with HTTP services but how to easily unit [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="padding-right:0;margin-top:3px"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.newsplore.com%2F2010%2F02%2F09%2Funit-testing-with-httpclient"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.newsplore.com%2F2010%2F02%2F09%2Funit-testing-with-httpclient" height="61" width="51" /></a></div><p>I want to write testable code and occasionally I bump into frameworks that make it challenging to unit test. Ideally I want to inject a service stub into my code then control the stub&#8217;s behavior based on my testing needs.<br />
<a href='http://hc.apache.org/httpclient-3.x/'>Commons Http Client</a> from Jakarta facilitates integration with HTTP services but how to easily <i>unit test</i> code that depends on the HttpClient library? Turns out it&#8217;s not that hard.<br />
I&#8217;ll cover both 1.3 and the newer 1.4 versions of the library since the older v1.3 is still widely used.<br />
Here&#8217;s some typical service (HttpClient v1.3) we want to test. It returns the remote HTML page title:</p>
<pre>
public class RemoteHttpService {
   private HttpClient client;

   public String getPageTitle(String uri)  throws IOException {
     String contentHtml = fetchContent(uri);
     Pattern p = Pattern.compile("&lt;title&gt;(.*)&lt;/title&gt;");
     Matcher m = p.matcher(contentHtml);
     if(m.find()) {
        return m.group(1);
     }
     return null;
   }

   private String fetchContent(String uri)  throws IOException {
      HttpMethod method = new GetMethod("http://blog.newsplore.com/" + uri);
      int responseStatus = client.executeMethod(method);
      if(responseStatus != 200) {
        throw new IllegalStateException("Expected HTTP response status 200 " +
"but instead got [" + responseStatus + "]");
      }
      byte[] responseBody = method.getResponseBody();
      return new String(responseBody, "UTF-8");
   }

   public void setHttpClient(HttpClient client) {
      this.client = client;
   }
}
</pre>
<p>with the HttpClient is injected at runtime (via some IoC container or explicitly).<br />
To be able to unit-test this code we have to come-up with a stubbed version of the HttpClient and emulate the GET method. </p>
<p><span id="more-1442"></span><br />
 What we really want is to be able to control the byte array returned by method.getResponseBody() and although we can inject a mocked HttpClient, the actual class that is responsible for producing the response body is GetMethod which is instantiated (and completely encapsulated) in the method body so we can&#8217;t inject a stubbed GetMethod version directly.<br />
The solution is to create a simple HttpClient mock that is able to control the response status and response body. Here it is:</p>
<pre>
package org.apache.commons.httpclient;

import org.apache.commons.httpclient.*;

public class HttpClientMock extends HttpClient {
   private int expectedResponseStatus;
   private String expectedResponseBody;
   public HttpClientMock (int responseStatus, String responseBody) {
      this.expectedResponseStatus = responseStatus;
      this.expectedResponseBody = responseBody;
   }
   @Override
   public int executeMethod(HttpMethod method) {
      ((HttpMethodBase)method).setResponseStream(
new ByteArrayInputStream(expectedResponseBody.getBytes("UTF-8")));
      return expectedResponseStatus;
   }
}
</pre>
<p>There are two things to notice: Firstly, I placed HttpClientMock in the org.apache.commons.httpclient package to be able to have access to the protected member HttpMethodBase:setResponseStream. Secondly, I downcasted HttpMethod to HttpMethodBase to get access to setResponseStream (it&#8217;s safe since all concrete HttpMethods (GetMethod, PostMethod, etc) inherit from it).</p>
<p>Now I can unit test RemoteHttpService like this:</p>
<pre>
public class RemoteHttpServiceTest {
   private RemoteHttpService remoteHttpService = new RemoteHttpService();

   @Test
   public void extractTitleResponseOK()  throws IOException {
      String pageTitle = "A Title";
      String responseBody = "&lt;title&gt;" + pageTitle + "&lt;/title&gt;";
      HttpClientMock mockHttpClient = new HttpClientMock(200, responseBody);
      remoteHttpService.setHttpClient(mockHttpClient);
      String resultedPageTitle = remoteHttpService.getPageTitle(""); //home page
      Assert.assertTrue(pageTitle.equals(resultedPageTitle));
   }
}
</pre>
<p>I can also add a negative test:</p>
<pre>
   @Test(expected = IllegalStateException.class)
   public void respondsWithInternalServerError()  throws IOException {
      HttpClientMock mockHttpClient = new HttpClientMock(500, "");
      remoteHttpService.setHttpClient(mockHttpClient);
      remoteHttpService.getPageTitle("");
   }
</pre>
<p>For HttpClient version 4.x here&#8217;s the refactored service code :</p>
<pre>
   private String fetchContent(String uri) {
        HttpGet httpget = new HttpGet("http://blog.newsplore.com/" + uri);
        HttpResponse response = client.execute(httpget);
        int responseStatus = response.getStatusLine().getStatusCode();
        if(responseStatus != 200) {
           throw new IllegalStateException("Expected HTTP response status 200 " +
"but instead got [" + responseStatus + "]");
        }
        InputStream responseStream = response.getEntity().getContent();
        byte[] responseBytes = IOUtils.toByteArray(responseStream);
        return new String(responseBytes, "UTF-8");
   }
</pre>
<p>Turns out that implementing a HttpClient mock by extending the DefaultHttpClient (the provided implementation of HttpClient) is not easy. The method I want to override is <i>public HttpResponse execute(HttpUriRequest request) </i> which is marked &#8216;final&#8217; and the code in DefaultHttpClient looks just too complex to inject stubbed behavior.<br />
What we actually want is to be able to control the return of the aforementioned &#8216;execute&#8217; method since it encapsulates the response status and body (better encapsulation than HttpClient 1.3 if you noticed).<br />
Luckily in this case we can use a readily available mocking framework, Mockito that can stub this entire method and return an HttpResponse that we instantiate with the needed status and response body. Here&#8217;s how to rewrite the tests using it:</p>
<pre>
@Test
public void extractTitleResponseOK() throws IOException {
	String pageTitle = "A Title";
	String responseBody = "";
	HttpResponse response = prepareResponse(200, responseBody);
	HttpClient mockHttpClient = Mockito.mock(HttpClient.class);
	Mockito.when(mockHttpClient.execute(Mockito.any(HttpUriRequest.class)))
			.thenReturn(response);

	remoteHttpService.setHttpClient(mockHttpClient);
	String resultedPageTitle = remoteHttpService.getPageTitle(""); // home page
	Assert.assertTrue(pageTitle.equals(resultedPageTitle));
}

@Test(expected = IllegalStateException.class)
public void respondsWithInternalServerError() throws IOException {
	HttpClient mockHttpClient = Mockito.mock(HttpClient.class);
	HttpResponse response = prepareResponse(500, "");
	Mockito.when(mockHttpClient.execute(Mockito.any(HttpUriRequest.class)))
			.thenReturn(response);
	remoteHttpService.setHttpClient(mockHttpClient);
	remoteHttpService.getPageTitle("");
}

private HttpResponse prepareResponse(int expectedResponseStatus,
               String expectedResponseBody) {
      HttpResponse response = new BasicHttpResponse(new BasicStatusLine(
    		  new ProtocolVersion("HTTP", 1, 1), expectedResponseStatus, ""));
      response.setStatusCode(expectedResponseStatus);
      try {
		response.setEntity(new StringEntity(expectedResponseBody));
	} catch (UnsupportedEncodingException e) {
		throw new IllegalArgumentException(e);
	}
	return response;
}
</pre>
<p>The meat of the above code is</p>
<pre>
HttpClient mockHttpClient = Mockito.mock(HttpClient.class);
HttpResponse response = prepareResponse(...);
Mockito.when(mockHttpClient.execute(Mockito.any(HttpUriRequest.class)))
	.thenReturn(response);
</pre>
<p>that instructs the mocked HttpClient to return a HttpResponse that is instantiated in the test context (seeded if you like) when &#8216;execute&#8217; is called (check Mockito documentation for more details on the syntax).</p>
<p>That&#8217;s it. Happy testing.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.newsplore.com/2010/02/09/unit-testing-with-httpclient/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Spincloud, now with worldwide forecast</title>
		<link>http://blog.newsplore.com/2009/12/13/spincloud-now-with-worldwide-forecast</link>
		<comments>http://blog.newsplore.com/2009/12/13/spincloud-now-with-worldwide-forecast#comments</comments>
		<pubDate>Mon, 14 Dec 2009 00:33:19 +0000</pubDate>
		<dc:creator>Florin</dc:creator>
				<category><![CDATA[projects]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[data freedom]]></category>
		<category><![CDATA[forecast]]></category>
		<category><![CDATA[weather]]></category>

		<guid isPermaLink="false">http://blog.newsplore.com/?p=1395</guid>
		<description><![CDATA[In my constant search for free weather data for Spincloud, a short while ago I have found a gem: free forecast data offered by the progressive Norwegian Meteorologic Institute. The long range forecast coverage is fairly thorough and covers most more than 2700 locations worldwide. I am happy to announce that I have extended spincloud.com [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="padding-right:0;margin-top:3px"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.newsplore.com%2F2009%2F12%2F13%2Fspincloud-now-with-worldwide-forecast"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.newsplore.com%2F2009%2F12%2F13%2Fspincloud-now-with-worldwide-forecast" height="61" width="51" /></a></div><p>In my constant search for free weather data for Spincloud, a short while ago I have found a gem: free forecast data offered by the progressive Norwegian Meteorologic Institute. The long range forecast coverage is fairly  thorough and covers most more than 2700 locations worldwide. I am happy to announce that I have extended <a href='http://spincloud.com'>spincloud.com</a> to include it.</p>
<table>
<tr>
<td><img src="http://blog.newsplore.com/wp-content/uploads/2009/12/worldwide_fcast.png" alt="worldwide_fcast" width="550" height="280" class="alignnone size-full wp-image-1396" /></td>
<td>&nbsp;&nbsp;&nbsp;</td>
</td>
</tr>
</table>
<p>The data is refreshed every hour and the forecast range is available for the next seven days. You can bookmark any <a href='http://www.spincloud.com:8080/weather/2775220'>location</a> or subscribe to weather reports via RSS.<br />
On a different but related note, I can only be thankful for the free data offered by various meteorological organizations that allows Spincloud to exist and I believe in freeing public data (weather related and otherwise) as it belongs to the public that finances government and inter-government agencies in the first place. The Norwegian Met Institute is a great example for freeing its data and I am saluting them for making the right decision.<br />
Now if only all such progressive Meteorological institutes around the world would agree on a common format for disseminating their data, it would make developers like me a tad happier&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.newsplore.com/2009/12/13/spincloud-now-with-worldwide-forecast/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Continuous everything?</title>
		<link>http://blog.newsplore.com/2009/10/15/continuous-everything</link>
		<comments>http://blog.newsplore.com/2009/10/15/continuous-everything#comments</comments>
		<pubDate>Thu, 15 Oct 2009 06:16:09 +0000</pubDate>
		<dc:creator>Florin</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://blog.newsplore.com/?p=1376</guid>
		<description><![CDATA[I admit that I regard automation as a dull but vital part in the success of a project. Automation had evolved into Continuous Integration, a powerful toolset allowing frequent and regular building and testing of the code. I won&#8217;t get into what CI is (check the internets). Instead, I am going to explore a couple [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="padding-right:0;margin-top:3px"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.newsplore.com%2F2009%2F10%2F15%2Fcontinuous-everything"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.newsplore.com%2F2009%2F10%2F15%2Fcontinuous-everything" height="61" width="51" /></a></div><p>I admit that I regard automation as a dull but vital part in the success of a project. Automation had evolved into <a href="http://en.wikipedia.org/wiki/Continuous_integration">Continuous Integration</a>, a powerful toolset allowing frequent and regular building and testing of the code. I won&#8217;t get into what CI is (<a href="http://martinfowler.com/articles/continuousIntegration.html">check</a> the internets). Instead, I am going to explore a couple of aspects of CI that can be added to the artifacts of the development process and note some others that cannot.</p>
<p><b>Continuous performance</b><br />
You wrote performance tests. You can run performance tests by firing a battery of tests from a client machine and targeted on an arbitrary environment where the application lives. The test results are collected on the client and you can publish them on a web server. Why not automating this completely then? To accomplish this, automate the execution, gathering and publishing of the performance results. Daily performance indicators not only increase visibility of the progress of the application but it becomes much easier to fix a performance degradation on a daily changeset than between two releases. There are a couple of factors that may add complexity to establishing performance tests:<br />
<i>Dealing with dependencies</i><br />
The obvious rule of thumb is to minimize dependencies. However, if there still are dependencies on other (perhaps external) systems, use mocks and to isolate the system you&#8217;re testing for performance. We&#8217;re talking about nightly performance tests so don&#8217;t put unnecessary stress where you shouldn&#8217;t.<br />
Finally, the main artifact of the final integration (done once per iteration) is a running environment where all components run together, in a production-like setup. Use this environment to run your system performance test where you measure the current performance against the baseline.<br />
<i>Measuring relative performance</i><br />
The environment you&#8217;re using for the nightly PT cycle most likely will not be a perfect mirror of production (especially true when dealing with geographically distributed systems). Use common-sense to establish the ratio between the two environments then derive rough production performance numbers using it (assuming a linear CPU/Throughput relationship).</p>
<p><b>Continuous deployment</b><br />
This is as simple as it sounds: automate the install. Make it dead easy to deploy the application in any environment by providing installation scripts. Simplify the configuration down to a single file that is self-documented and easily understood by non-programmers (read Operations Teams). The goal here is to unlock a powerful tool: making the application installable and upgradable with a click of a button. If all the other pieces of the continuum are in place then you could confidently deploy your application in production it on a much tighter release cycle, even on a daily basis. Deployment and integration become tasks in the background rather than first-class events.</p>
<p><b>More continuous</b><br />
Since I am just fresh off the Agile Testing Days conference and I have learned a few more Cs from the distinguished speakers which I term as Soft Cs since they involve constant human engagement:<br />
- Continuous learning (Declan Whelan)<br />
- Continuous process improvement (Stuart Reid)<br />
- Continuous acceptance testing (i.e. stakeholder signoff at the end of every sprint) &#8211; Anko Tijman<br />
- Continuous customer involvement (Anko Tijman)</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.newsplore.com/2009/10/15/continuous-everything/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>blog.newsplore.com is one year old!</title>
		<link>http://blog.newsplore.com/2009/10/03/blog-newsplore-com-is-one-year-old</link>
		<comments>http://blog.newsplore.com/2009/10/03/blog-newsplore-com-is-one-year-old#comments</comments>
		<pubDate>Sat, 03 Oct 2009 19:55:12 +0000</pubDate>
		<dc:creator>Florin</dc:creator>
				<category><![CDATA[software]]></category>

		<guid isPermaLink="false">http://blog.newsplore.com/?p=1374</guid>
		<description><![CDATA[Sep. 15 came and went and I didn&#8217;t realize that this blog is one year old. I didn&#8217;t post in the last few months but this is because I have been busy moving across the world from Toronto back to Europe (I&#8217;m in Berlin now), becoming a father (&#8220;the best job in the world&#8221;) and [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="padding-right:0;margin-top:3px"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.newsplore.com%2F2009%2F10%2F03%2Fblog-newsplore-com-is-one-year-old"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.newsplore.com%2F2009%2F10%2F03%2Fblog-newsplore-com-is-one-year-old" height="61" width="51" /></a></div><p>Sep. 15 came and went and I didn&#8217;t realize that this blog is one year old. I didn&#8217;t post in the last few months but this is because I have been busy moving across the world from Toronto back to Europe (I&#8217;m in Berlin now), becoming a father (&#8220;the best job in the world&#8221;) and taking a new job (LBS, yes!).<br />
Things are happening, wheels are in motion and there&#8217;s still a lot to write about. </p>
<p>Stay tuned!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.newsplore.com/2009/10/03/blog-newsplore-com-is-one-year-old/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

