<?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; REST</title>
	<atom:link href="http://blog.newsplore.com/tag/rest/feed" rel="self" type="application/rss+xml" />
	<link>http://blog.newsplore.com</link>
	<description>Everything beta</description>
	<lastBuildDate>Tue, 07 Sep 2010 10:40:06 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<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>
<p class="fbconnect_share"><fb:share-button class="url" href="http://blog.newsplore.com/2010/06/27/building-a-content-aggregation-service-with-node-js" /></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>2</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>
<p class="fbconnect_share"><fb:share-button class="url" href="http://blog.newsplore.com/2010/02/23/spring-mvc-3-0-rest-rebuttal" /></p>]]></content:encoded>
			<wfw:commentRss>http://blog.newsplore.com/2010/02/23/spring-mvc-3-0-rest-rebuttal/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Upgrading to Spring 3.0</title>
		<link>http://blog.newsplore.com/2009/03/07/upgrading-to-spring-30</link>
		<comments>http://blog.newsplore.com/2009/03/07/upgrading-to-spring-30#comments</comments>
		<pubDate>Sat, 07 Mar 2009 16:05:12 +0000</pubDate>
		<dc:creator>Florin</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://blog.newsplore.com/?p=773</guid>
		<description><![CDATA[In the spirit of beta I&#8217;m upgrading spincloud.com to Spring 3.0. I&#8217;m using version 2.5.6 currently but it&#8217;s missing REST support and I had to use Carbonfive&#8217;s REST library which worked like a charm. Now it&#8217;s time to get back under Spring&#8217;s fold and use their built-in REST support. Spring 3 opens the door to [...]]]></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%2F03%2F07%2Fupgrading-to-spring-30"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.newsplore.com%2F2009%2F03%2F07%2Fupgrading-to-spring-30" height="61" width="51" /></a></div><p>
<div align='justify'>In the spirit of beta I&#8217;m upgrading <a href='http://spincloud.com'>spincloud.com</a> to Spring 3.0. I&#8217;m using version 2.5.6 currently but it&#8217;s missing REST support and I had to use Carbonfive&#8217;s <a href='http://www.carbonfive.com/community/archives/2007/06/parameterized_rest_urls_with_spring_mvc.html'>REST library</a> which worked like a charm. Now it&#8217;s time to get back under Spring&#8217;s fold and use their built-in REST support. Spring 3 opens the door to a lot of new features so I&#8217;m eager to try it.</p>
<p>I&#8217;m using Maven2 to get the jars and Ant to build the project. To fetch Spring 3.0 binaries, you have to add the following repository if you don&#8217;t have it:</p></div>
<pre>
&lt;repository&gt;
  &lt;id&gt;SpringSource Enterprise Bundle Repositorys&lt;/id&gt;
  &lt;url&gt;http://repository.springsource.com/maven/bundles/milestone&lt;/url&gt;
&lt;/repository&gt;
</pre>
<p>and the spring packages that you need since the packaging has changed from 2.5.x. Instead of a single spring.jar file, now there is one per feature so you have to sort out what jars to include in the project. I ended up with the following:</p>
<pre>
  &lt;properties&gt;
      &lt;spring.version&gt;3.0.0.M2&lt;/spring.version&gt;
  &lt;/properties&gt;
  &lt;dependencies&gt;
   ...
  &lt;dependency&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;org.springframework.core&lt;/artifactId&gt;
      &lt;version&gt;${spring.version}&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;org.springframework.web&lt;/artifactId&gt;
      &lt;version&gt;${spring.version}&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;org.springframework.transaction&lt;/artifactId&gt;
      &lt;version&gt;${spring.version}&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;org.springframework.orm&lt;/artifactId&gt;
      &lt;version&gt;${spring.version}&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;org.springframework.jdbc&lt;/artifactId&gt;
      &lt;version&gt;${spring.version}&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;org.springframework.web.servlet&lt;/artifactId&gt;
      &lt;version&gt;${spring.version}&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;org.springframework.context&lt;/artifactId&gt;
      &lt;version&gt;${spring.version}&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;org.springframework.aop&lt;/artifactId&gt;
      &lt;version&gt;${spring.version}&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;org.springframework.expression&lt;/artifactId&gt;
      &lt;version&gt;${spring.version}&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;org.springframework.test&lt;/artifactId&gt;
      &lt;version&gt;${spring.version}&lt;/version&gt;
    &lt;/dependency&gt;
  &lt;/dependencies&gt;
</pre>
<p>Once the jars are brought, I&#8217;ve replaced my old jarfiles with the all-new M2s then fired the build target.<br />
The first issue I found was with the asm version.<br />
  <span id="more-773"></span><br />
Spring 2.5 uses a repackaged asm version 2.2.3 (more info <a href='http://blog.springsource.com/2007/06/11/asm-version-incompatibilities-using-spring-autowired-with-hibernate/'>here</a>). The new Spring 3.0 M2 doesn&#8217;t package it anymore ( see <a href='http://blog.springsource.com/2009/02/25/spring-framework-30-m2-released/#comment-147950'>comment</a>) so I had to add it manually. I had to add the two asm 2.2.3 jars in order to resolve this dependency:</p>
<pre>
   &lt;dependency&gt;
     &lt;groupId&gt;asm&lt;/groupId&gt;
     &lt;artifactId&gt;asm-commons&lt;/artifactId&gt;
     &lt;version&gt;2.2.3&lt;/version&gt;
   &lt;/dependency&gt;
   &lt;dependency&gt;
     &lt;groupId&gt;asm&lt;/groupId&gt;
     &lt;artifactId&gt;asm&lt;/artifactId&gt;
     &lt;version&gt;2.2.3&lt;/version&gt;
   &lt;/dependency&gt;
</pre>
<p>After refreshing the jars and redeployed, I hit the first roadblock, a ClassNoDefFoundError:</p>
<pre>
Initialization of bean failed; nested exception is
java.lang.NoClassDefFoundError: Could not initialize class
net.sf.cglib.proxy.Enhancer
...
Caused by: java.lang.ClassNotFoundException:
org.objectweb.asm.CodeVisitor
</pre>
<p>Odd, I didn&#8217;t have this error before but as it turns out, I was using a cglib version 2.1.3 which has a hard dependency on asm and I actually had an asm jar version 1.5.3 packaged along with the other jar dependencies. On top of this, there is a problem with an <a href='http://www.antlr.org/'>antlr</a> version conflict. Different versions of antlr are required by Spring 3.0 and Hibernate 3.3.1 which I&#8217;m also using. This is Jar hell! So I put together a version requirment matrix to sort-out the dependencies between these libraries:</p>
<table border='1' style='text-align: center;' align='center'>
<tr>
<td></td>
<td>&nbsp;&nbsp;&nbsp;&nbsp;antlr&nbsp;&nbsp;&nbsp;&nbsp;</td>
<td>&nbsp;&nbsp;&nbsp;&nbsp;cglib&nbsp;&nbsp;&nbsp;&nbsp;</td>
<td>&nbsp;&nbsp;&nbsp;&nbsp;asm&nbsp;&nbsp;&nbsp;&nbsp;</td>
</tr>
<tr>
<td>&nbsp;&nbsp;&nbsp;Spring 3.0 M2&nbsp;&nbsp;&nbsp;</td>
<td>3.0.1</td>
<td>&nbsp;&nbsp;2.1.x +, depends on asm 1.5.3&nbsp;&nbsp;</td>
<td>2.2.3</td>
</tr>
<tr>
<td>&nbsp;&nbsp;&nbsp;Hibernate 3.3.1&nbsp;&nbsp;&nbsp;</td>
<td>2.7.x</td>
<td> none </td>
<td>2.2.3</td>
</tr>
</table>
<p>Fortunately the Hibernate folks have <a href='http://opensource.atlassian.com/projects/hibernate/browse/HHH-2506'>changed</a> the default bytecode generation library to javassist starting with v3.2.2. The bummer is the cglib dependency on asm 1.5.3 since this version is in conflict with asm 2.2.3 required by both Spring and Hibernate. The solution is to use a repackaged cglib as explained <a href='http://jira.springframework.org/browse/SPR-3856'>here</a>.<br />
To get the nodep version of cglib, I added the following snippet in my pom.xml file:</p>
<pre>
&lt;dependency&gt;
  &lt;groupId&gt;cglib&lt;/groupId&gt;
  &lt;artifactId&gt;cglib-nodep&lt;/artifactId&gt;
  &lt;version&gt;2.2&lt;/version&gt;
&lt;/dependency&gt;
</pre>
<p>I&#8217;m taking the opportunity and upgrade to the newer version 2.2 of cglib.<br />
Next is antlr. Spring requires a different version of antlr than Hibernate but fortunately antlr has changed the package notation from antlr.* in v2.x to org.antlr.* in v3.x so it&#8217;s safe to include both jars. Let&#8217;s get both versions through Maven:</p>
<pre>
   &lt;dependency&gt;
     &lt;groupId&gt;antlr&lt;/groupId&gt;
     &lt;artifactId&gt;antlr&lt;/artifactId&gt;
     &lt;version&gt;2.7.7&lt;/version&gt;
   &lt;/dependency&gt;
   &lt;dependency&gt;
     &lt;groupId&gt;org.antlr&lt;/groupId&gt;
     &lt;artifactId&gt;antlr&lt;/artifactId&gt;
     &lt;version&gt;3.0.1&lt;/version&gt;
   &lt;/dependency&gt;
</pre>
<p>Here&#8217;s the mix of jars that works for me with Spring &amp; Hibernate:</p>
<table border='1' style='text-align: center;' align='center'>
<tr>
<td></td>
<td>antlr</td>
<td>cglib</td>
<td>asm</td>
</tr>
<tr>
<td rowspan='2'>&nbsp;&nbsp;Spring 3.0 M2 &amp;<br />&nbsp;&nbsp;Hibernate 3.3.1&nbsp;&nbsp;</td>
<td>&nbsp;&nbsp;antlr-2.7.7.jar &amp; <br />&nbsp;&nbsp;antlr-3.0.1.jar&nbsp;&nbsp;</td>
<td>&nbsp;&nbsp;cglib-nodep-2.2.jar&nbsp;&nbsp;</td>
<td>&nbsp;&nbsp;asm-2.2.3.jar&nbsp;&nbsp;</td>
</tr>
</table>
<p>I can&#8217;t help but notice the compatibility problems with using the Spring &amp; Hibernate mix. It wasn&#8217;t easy to fix them and it still feels more of a hack than an actual solution. In Spring&#8217;s defense, this is a milestone version so I should expect some wrinkles. I had similar issues when upgrading Hibernate a while back. Hibernate was the first to change their packaging to use feature-centric jars (I think). I recall having issues around antlr and asm. I remember being reluctant at first about the new dependency to javassist but it worked just fine.</p>
<p>Next on the list is refactoring the controllers to use the new REST support of Spring. The majority of my controllers are extending from org.springframework.web.servlet.mvc.AbstractController so I&#8217;ll upgrade them to use <a href='http://static.springframework.org/spring/docs/2.5.x/reference/mvc.html#mvc-ann-controller'>@Controller</a> stereotype. I&#8217;m already familiar with @Controller, I&#8217;m using it to route all top URLs found on Spincloud&#8217;s header (i.e. <a href='http://spincloud.com/features'>features</a>). I use a simple approach: drop the inheritance to <a href='http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/web/servlet/mvc/AbstractController.html'>AbstractController</a> and change handleRequestInternal:</p>
<pre>
@Controller
public class WeatherDetailsController extends AbstractController {
...
  @Override
   protected ModelAndView handleRequestInternal(HttpServletRequest request,
     HttpServletResponse response) throws Exception {
    //parse URI to extract stationIDs
...
  }
}
</pre>
<p>with the much cooler:</p>
<pre>
@Controller
public class WeatherDetailsController {
...
 @RequestMapping(value="/weather/{stationIds}", method = RequestMethod.GET)
 public ModelAndView displayWeather(@PathVariable("stationIds") String idz,
   HttpServletRequest request, HttpServletResponse response) {
...
  }
}
</pre>
<p>Last, remove the carbonfive HandlerMapping bean in the spring servlet XML which used to look like this:</p>
<pre>
 &lt;bean class="carbonfive.spring.web.pathparameter.ParameterizedUrlHandlerMapping"&gt;
  &lt;property name="alwaysUseFullPath" value="true"/&gt;
  &lt;property name="mappings"&gt;
   &lt;props&gt;
    &lt;prop key="/weather/*"&gt;weatherDetailsController&lt;/prop&gt;
   &lt;/props&gt;
  &lt;/property&gt;
 &lt;/bean&gt;
</pre>
<p>Deployed and started the container successfully but when I hit a URL that was supposed to be routed through the new controller, I got the following error:</p>
<pre>
2009-03-07 20:55:49,072: WARN  PageNotFound:1017
 No mapping found for HTTP request with URI [/weather/15150] in
DispatcherServlet with name 'weather'
</pre>
<p>Bummer: the URL is not routed to any controller. I initially suspected the DefaultAnnotationHandlerMapping I was using was to blame but after searching on the interweb and finding nothing else worthy and a couple of hours of research in my own code, I discovered that the problem was in web.xml. I had fine grained servlet-mapping URLs, including one that should have routed all URLs starting with /weather  that looked like this: </p>
<pre>
 &lt;servlet-mapping&gt;
   &lt;servlet-name&gt;weather&lt;/servlet-name&gt;
   &lt;url-pattern&gt;/weather/*&lt;/url-pattern&gt;
 &lt;/servlet-mapping&gt;
</pre>
<p>which is not good anymore. After checking the <a href='https://src.springframework.org/svn/spring-framework/tags/spring-framework-3.0.0.M2/org.springframework.samples.petclinic/src/main/webapp/WEB-INF/web.xml'>web.xml</a> file in the Petstore example, I noticed that the servlet mappings can use the greedy &lt;url-pattern&gt;/&lt;/url-pattern&gt; to route to one controller then more specific patterns for routing to other controllers. Since I have more than one controller, I changed the mappings like below:</p>
<pre>
 &lt;servlet-mapping&gt;
   &lt;servlet-name&gt;weather&lt;/servlet-name&gt;
   &lt;url-pattern&gt;/&lt;/url-pattern&gt;
 &lt;/servlet-mapping&gt;
 &lt;servlet-mapping&gt;
   &lt;servlet-name&gt;tag&lt;/servlet-name&gt;
   &lt;url-pattern&gt;/tag/*&lt;/url-pattern&gt;
 &lt;/servlet-mapping&gt;
</pre>
<div align='justify'>
<p>Tested again the URL and it correctly routed to the right controller.<br />
I was home-free after this bump. Cleaned-up the code, removed lots of XML (always popular), dropped the -now obsolete- URL parsing and validation and now I&#8217;m contemplating a much cleaner and more concise code.</p>
<p></p>
<p>There are other features that come with this Spring upgrade, detailed <a href='http://blog.springsource.com/2009/02/25/spring-framework-30-m2-released/'>here</a> and <a href='http://springinpractice.com/2008/12/02/new-stuff-in-spring-30/'>here</a>. I especially like the sound of the promised scheduling namespace since I currently have to maintain long XML files to configure the timers that trigger the fetching of weather data. This will be one of the few remaining pieces of XML that I still have. A nice touch is the new <a href='http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/CookieValue.html'>@CookieValue</a>.<br />
Moving forward, Spring promises to deliver a host of exciting features:<br />
- Declarative validation (JSR 303). I&#8217;m really excited about this one having used Hibernate&#8217;s JSR 303 implementation. I love this JSR, it&#8217;s a step in the right direction!<br />
- JPA 2.0 support and early JEE 6 support. Details about what JEE6 will bring are available <a href='http://www.theserverside.com/tt/articles/article.tss?l=JavaEE6Overview'>here</a>.<br />
- Spring Portlet MVC, based on the Portlet 2.0 API (JSR-286)<br />
- Annotation based factory methods (working towards XML configuration obliteration). I use factory methods so I like this one too.<br />
- A rumor that a JSON view will be available. I&#8217;ve written my own JSONServiceExporter and a JSONView for <a href="http://spincloud.com">Spincloud</a> (I use JSON for all front-end data pipes) but I&#8217;d switch to a leaner solution if available.</p>
<p>&#8230;and much more.</p>
<p><del datetime="2009-03-10T23:13:09+00:00">I&#8217;d like to see the annotation-based </del><a href='http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-scopes'><del datetime="2009-03-10T23:13:09+00:00">bean scopes</del></a>   (already available through Spring&#8217;s <a href='http://static.springframework.org/spring-javaconfig/docs/1.0.0.M4/reference/html/ch02s02.html#scoped-proxy'>@ScopedProxy</a>,  part of the JavaConfig project). Also, better support for multiple data sources in a non-JTA environment (I&#8217;ll detail my problems with it in another post).</p>
<p>For now, I&#8217;m content. Except for a few (expected) wrinkles, Spring delivers again and it succeeds in keeping things exciting in the Java space. Way to go guys!
</p></div>
<p class="fbconnect_share"><fb:share-button class="url" href="http://blog.newsplore.com/2009/03/07/upgrading-to-spring-30" /></p>]]></content:encoded>
			<wfw:commentRss>http://blog.newsplore.com/2009/03/07/upgrading-to-spring-30/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>REST is DSL</title>
		<link>http://blog.newsplore.com/2008/11/06/rest-is-dsl</link>
		<comments>http://blog.newsplore.com/2008/11/06/rest-is-dsl#comments</comments>
		<pubDate>Fri, 07 Nov 2008 03:18:37 +0000</pubDate>
		<dc:creator>Florin</dc:creator>
				<category><![CDATA[opinions]]></category>
		<category><![CDATA[DSL]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://blog.newsplore.com/?p=238</guid>
		<description><![CDATA[I like RESTful URLs. They clearly express the intent of the provided resource. We humans speak a language close to REST when we talk to The Internet.  Take a look at Google&#8217;s RESTful search query, probably the most used RESTful URL ever: http://www.google.com/search?q=your-terms-of-choice in freeform language this translates to: &#8220;Google, search for this term.&#8221; How [...]]]></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%2F2008%2F11%2F06%2Frest-is-dsl"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.newsplore.com%2F2008%2F11%2F06%2Frest-is-dsl" height="61" width="51" /></a></div><p>I like <a title="REST" href="http://en.wikipedia.org/wiki/Representational_State_Transfer">REST</a>ful URLs. They clearly express the intent of the provided resource. We humans speak a language close to REST when we talk to The Internet. </p>
<p>Take a look at Google&#8217;s RESTful search query, probably the most used RESTful URL ever:</p>
<pre>http://www.google.com/search?q=your-terms-of-choice</pre>
<p>in freeform language this translates to: &#8220;Google, search for this term.&#8221;</p>
<p>How about the Flickr RESTful tag cluster search service:</p>
<pre>http://api.flickr.com/services/rest/?method=flickr.tags.getClusters&amp;
api_key=a6f11b67ae348a7b3f2da0d865b8bc1d&amp;tag=Berlin</pre>
<p>In Flickr lingo this means: &#8220;Fetch all tag clusters for the &#8216;Berlin&#8217; tag&#8221;.</p>
<p>It doesn&#8217;t take much to understand RESTful URLs. They speak the language of the domain they represent and therefore in the Web Services provider-consumer world:</p>
<p><b>The collection of all RESTful services provided by a domain represents its web-oriented Domain Specific Language.</b>  </p>
<p><a title="DSL" href="http://www.martinfowler.com/bliki/DomainSpecificLanguage.html">DSL</a>s have been around for a long time. For more information check Martin Fowler&#8217;s <a title="Fowler's DSL talk" href="http://www.infoq.com/presentations/domain-specific-languages">talk</a> on the subject.</p>
<p class="fbconnect_share"><fb:share-button class="url" href="http://blog.newsplore.com/2008/11/06/rest-is-dsl" /></p>]]></content:encoded>
			<wfw:commentRss>http://blog.newsplore.com/2008/11/06/rest-is-dsl/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
