<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:media="http://search.yahoo.com/mrss/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><title>Surya Suravarapu's Blog</title><link>http://www.suryasuravarapu.com</link><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/SuryaSuravarapusBlog" /><description>Ramblings on software and stuff related</description><language>en-US</language><lastBuildDate>Thu, 25 Apr 2013 10:20:01 PDT</lastBuildDate><generator>http://wordpress.org/?v=3.4.2</generator><sy:updatePeriod xmlns:sy="http://purl.org/rss/1.0/modules/syndication/">hourly</sy:updatePeriod><sy:updateFrequency xmlns:sy="http://purl.org/rss/1.0/modules/syndication/">1</sy:updateFrequency><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/SuryaSuravarapusBlog" /><feedburner:info uri="suryasuravarapusblog" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><itunes:explicit>no</itunes:explicit><itunes:subtitle>Ramblings on software and stuff related</itunes:subtitle><geo:lat>40.089905</geo:lat><geo:long>-75.641249</geo:long><image><link>http://www.feedburner.com</link><url>http://www.feedburner.com/fb/images/pub/fb_pwrd.gif</url><title>This Feed Powered by FeedBurner.com</title></image><feedburner:emailServiceId>SuryaSuravarapusBlog</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><feedburner:browserFriendly>This is an XML content feed. It is intended to be viewed in a newsreader or syndicated to another site, subject to copyright and fair use.</feedburner:browserFriendly><item><title>Scala Parser Combinators =&gt; Win</title><link>http://feedproxy.google.com/~r/SuryaSuravarapusBlog/~3/13Sf31ja3NA/scala-parser-combinators-win.html</link><category>Scala</category><category>REST</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Surya Suravarapu</dc:creator><pubDate>Wed, 27 Apr 2011 02:56:32 PDT</pubDate><guid isPermaLink="false">http://www.suryasuravarapu.com/?p=1403</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Parser_combinator">Parser combinators</a> is such a cool concept, very nice tool in your toolkit if you are working on external DSLs. I've been playing with them a little bit recently. Combining different parsers using higher order functions is fun, especially if you are using Scala.</p>
<p>Parser combinators are provided as a library in Scala over the core language. Let's use an example to walk through the details ...</p>
<p><strong>Problem:</strong> HTTP's accept header provides a way for the client to request what content-type it prefers. For this exercise let's just parse the header into a list of <code>AcceptHeader</code> objects. Sorting the list based on the quality factor (or q value) is trivial and not related with this discussion, so skipping.</p>
<p>According to the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">HTTP specification</a> the grammar for the Accept header is  --</p>
<p><code>Accept = "Accept" ":" #( media-range [ accept-params ] )<br />
media-range = ( "*/*"<br />
| ( type "/" "*" )<br />
| ( type "/" subtype )<br />
) *( ";" parameter )<br />
accept-params  = ";" "q" "=" qvalue *( accept-extension )<br />
accept-extension = ";" token [ "=" ( token | quoted-string )<br />
</code></p>
<p>Example of such a header is: <code>application/html;q=0.8, text/*, text/xml, application/json;q=0.9</code></p>
<p><strong>Approach</strong></p>
<p>The goal now is to parse the header value into a list of <code>AcceptHeader</code> objects, where an <code>AcceptHeader</code> is defined as a case class:</p>
<p><script src="https://gist.github.com/943469.js?file=AcceptHeader.scala"></script><noscript>[If you don't see the code embedded, here is the <a href="https://gist.github.com/943469#file_accept_header.scala">direct link</a>]</noscript> </p>
<p>See below for a possible approach on parsing the accept header using the combinator technique:  <script src="https://gist.github.com/943469.js?file=AcceptHeaderParser.scala"></script><noscript>[If you don't see the code embedded, here is the <a href="https://gist.github.com/943469#file_accept_header_parser.scala">direct link</a>]</noscript> </p>
<p>Note: I did not implement accept-extension defined in the specification's grammar in this example.</p>
<p>Now let's look at various aspects of the code:<br />
[click on the image to enlarge]<br />
<a href="http://www.suryasuravarapu.com/wp-content/uploads/2011/04/parser-combinator.jpg" rel="lightbox[1403]"><img class="alignnone size-large wp-image-1410" title="Parser combinator" src="http://www.suryasuravarapu.com/wp-content/uploads/2011/04/parser-combinator-1024x158.jpg" alt="" width="600" height="92" /></a></p>
<ul>
<li> First look at the <code>lazy val acceptEntry</code>:
<ul>
<li><code>mediaType &lt; ~ "/"</code> indicates that result of parsing slash ("/") is irrelevant and only carry forward the result on the left (that's of the mediaType).</li>
<li><code>~</code> is a method in the Parsers trait that stands for sequential combinator.</li>
<li><code>opt</code> method stands for optional value for quality factor (q).</li>
<li><code>^^</code> is a method in the Parsers trait -- it has a parser on the left and a function on it's right (that's doing some case matching, in this case). If the parsing effort on the left is successful it applies the function on the right to that parse result.</li>
</ul>
</li>
<li>The subsequent lines expand and define each of the parsers defined in <code>acceptEntry</code>
<ul>
<li>regex is defined for media type and subtype allowing for alpha-numeric, hyphen (-) and asterisk(*) values</li>
<li>For qualityFactor: <code>";" ~&gt; "q" ~&gt; "=" ~&gt; floatingPointNumber</code> -- ignores all the parsed results on the left as we are only interested in knowing what the value of q is, which is defined as a <code>floatingPointNumber</code></li>
</ul>
</li>
<li>Now jump back to the first line which says accept is <code>rep1sep(acceptEntry, ",").</code><code> rep1sep</code> is a method in the Parsers trait. We are saying that the accept entry will repeat one or more times, and each entry is separated by a comma (",)</li>
</ul>
<p>You may test the functionality via<br />
<script src="https://gist.github.com/943469.js?file=AcceptHeaderTest.scala"></script><noscript>[If you don't see the code embedded, here is the <a href="https://gist.github.com/943469#file_accept_header_test.scala">direct link</a>]</noscript> </p>
<p><strong>Output:</strong> <code>List(AcceptHeader(application,html,0.8), AcceptHeader(text,*,1.0), AcceptHeader(text,xml,1.0), AcceptHeader(application,json,0.9))<br />
</code></p>
<p>We just scratched the surface here. <a href="http://debasishg.blogspot.com">Debasish Ghosh</a>'s <a href="http://www.manning.com/ghosh/">DSLs in Action</a> dedicated a chapter for parser combinators, which helped me quite a bit in furthering my understanding. (Highly recommend Ghosh's book if you are contemplating about implementing DSLs).</p>
<img src="http://feeds.feedburner.com/~r/SuryaSuravarapusBlog/~4/13Sf31ja3NA" height="1" width="1"/>]]></content:encoded><description>Parser combinators is such a cool concept, very nice tool in your toolkit if you are working on external DSLs. I've been playing with them a little bit recently. Combining different parsers using higher order functions is fun, especially if you are using Scala. Parser combinators are provided as a library in Scala over the [...]</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://www.suryasuravarapu.com/2011/04/scala-parser-combinators-win.html/feed</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">3</slash:comments><feedburner:origLink>http://www.suryasuravarapu.com/2011/04/scala-parser-combinators-win.html</feedburner:origLink></item><item><title>Book Review: Selenium 1.0 Testing Tools</title><link>http://feedproxy.google.com/~r/SuryaSuravarapusBlog/~3/zI14eMYqV8A/book-review-selenium-1-0-testing-tools.html</link><category>BookReview</category><category>Testing</category><category>Selenium</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Surya Suravarapu</dc:creator><pubDate>Thu, 10 Mar 2011 09:30:29 PST</pubDate><guid isPermaLink="false">http://www.suryasuravarapu.com/?p=1386</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<h3><img style=' float: left; padding: 4px; margin: 0 7px 2px 0;'  class="alignleft size-thumbnail wp-image-1392" title="Selenium-1.0-Testing Tools" src="http://www.suryasuravarapu.com/wp-content/uploads/2011/03/Selenium-1.0-Testing-Tools-150x150.jpg" alt="" width="150" height="150" />The Book</h3>
<p><strong>Title:</strong> <a href="https://www.packtpub.com/selenium-1-0-testing-tools-beginners-guide/book">Selenium 1.0 Testing Tools (Beginner's Guide)</a></p>
<p><strong>Author:</strong> David Burns</p>
<p><strong>Publishers:</strong> Packt Publishing</p>
<h3>Review</h3>
<p>First half of the book is dedicated to <a href="http://seleniumhq.org/projects/ide/">Selenium IDE</a> and the second half covers -- <a href="http://seleniumhq.org/projects/remote-control/">Selenium Remote Control</a> (RC), <a href="http://selenium-grid.seleniumhq.org/">Selenium Grid,</a> and discusses the upcoming changes in Selenium 2.0.</p>
<p>This is a how-to book, a detailed step-by-step guide, with several screenshots. The book starts off with the installation and setup of Selenium and then proceeds to cover Locators and Pattern Matching in the subsequent chapters. If you could identify the elements on the web page that's a battle half won in the test automation. Various techniques are in display to locate the elements including XPath, CSS, element IDs, link text. Pattern matching covers finding elements by using regular expressions and globs.</p>
<p>There is a lot of emphasis on Selenium IDE. If you are someone who are not too comfortable writing test scripts using Selenium RC (API-driven) you can take the best advantage of the bulk of the book. Later on in the book, the author discusses how you can convert your IDE-based tests to Selenium RC (as you get more familiar with APIs).</p>
<p>The discussion on the Remote Control and Grid is adequate. Integration of Selenium with JUnit and TestNG is nice, very handy if you would like to run your tests in parallel.</p>
<p>Given that the Selenium 2.0 is going to be released very soon (in the next couple of months?), I'm not so  sure why the author concentrated on 1.0 for the most part of the book. Last chapter of the book is dedicated to discuss Selenium 2.0 changes. If my understanding is correct, most of the impact from Selenium 2.0 is in the Remote Control side, merging <a href="http://code.google.com/p/selenium/wiki/GettingStarted">WebDriver</a> stuff. The book, in general, is organized very well. The only complaint I have in the organization is: in the earlier chapters, may be the author should have pointed out which APIs are changing or would get impacted because of Selenium 2.0.</p>
<p>This is a beginner's guide, as printed on the cover of the book. Nothing less, nothing more. If you are looking for more advanced techniques of  functional/acceptance testing, and want to learn internals of Selenium  then look elsewhere. But if you are starting out and have little or no familiarity with Selenium then this book can certainly help you to get upto speed real quick.</p>
<p>&nbsp;</p>
<img src="http://feeds.feedburner.com/~r/SuryaSuravarapusBlog/~4/zI14eMYqV8A" height="1" width="1"/>]]></content:encoded><description>The Book Title: Selenium 1.0 Testing Tools (Beginner's Guide) Author: David Burns Publishers: Packt Publishing Review First half of the book is dedicated to Selenium IDE and the second half covers -- Selenium Remote Control (RC), Selenium Grid, and discusses the upcoming changes in Selenium 2.0. This is a how-to book, a detailed step-by-step guide, [...]</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://www.suryasuravarapu.com/2011/03/book-review-selenium-1-0-testing-tools.html/feed</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">0</slash:comments><feedburner:origLink>http://www.suryasuravarapu.com/2011/03/book-review-selenium-1-0-testing-tools.html</feedburner:origLink></item><item><title>Conditional Requests with Lift</title><link>http://feedproxy.google.com/~r/SuryaSuravarapusBlog/~3/jjSfZIoyo8c/conditional-requests-with-lift.html</link><category>REST</category><category>Lift</category><category>Scala</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Surya Suravarapu</dc:creator><pubDate>Thu, 13 Jan 2011 08:36:11 PST</pubDate><guid isPermaLink="false">http://www.suryasuravarapu.com/?p=1329</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p><a href="http://en.wikipedia.org/wiki/HTTP_ETag">ETag</a> (or entity tag) values and/or Last modified time of the resource are typically used for this purpose. I'm only discussing ETags here, interchanging this with Last-modified time is trivial, so skipping.</p>
<p>In this post I'm concentrating on deep ETags, where application developer can generate and compare ETags based on the underlying domain objects, database tables, etc.</p>
<p>Other kind of ETags, the shallow ones, can be supported at the framework level. They rely on hash of the representations. A web framework can generate ETag value, and compare them with the representation from the response. Shallow ETags are useful with respect to saving bandwidth but does not eliminate the computation on the server side. (Expect a post on the shallow ETags soon).</p>
<h3>Conditional GET</h3>
<p>Conditional GET is a great way to conserve bandwidth. An intermediary cache may check with the origin server whether the resource has changed since it last received a representation. The server responds either with the new representation if the resource state changed or send back only the headers with <code>304 Not Modified</code> response.</p>
<p>Let's start with defining a <code>Product</code> class which is using Lift's <a href="http://www.assembla.com/wiki/show/liftweb/Mapper">Mapper</a> (as ORM). Also, note the use of <a href="http://scala-tools.org/mvnsites/liftweb-2.2/framework/scaladocs/net/liftweb/mapper/CreatedUpdated.html">CreatedUpdated</a> trait, this will automatically add two timestamp fields -- <code>createdAt</code> and <code>updatedAt</code> for insert and update operations respectively.<br />
<script src="https://gist.github.com/774649.js?file=Product.scala"></script><noscript>[If you don't see the code embedded, here is the <a href="https://gist.github.com/774649#file_product.scala">direct link</a>]</noscript></p>
<p>There are various strategies to generate ETags, I'm using the one that uses the <code>updatedAt</code> field (and use its <code>Long</code> value). Let's first see this in action and get back to implementation details in a bit. Using <a href="http://curl.haxx.se/">cURL</a> to test.</p>
<p>Request and Response for a <code>Product</code> of known <code>ID</code></p>
<p><img class="alignnone size-full wp-image-1355" title="GET" src="http://www.suryasuravarapu.com/wp-content/uploads/2011/01/condreq_GET_200.jpg" alt="" width="442" height="280" /></p>
<p>For subsequent requests the client sends the value of ETag provided by the server. See <code>If-None-Match</code> header in the request below. Adding this header makes the request a conditional one. If the resource doesn't change the server sends back only the headers with <code>304</code> header (see below).</p>
<p><img class="alignnone size-full wp-image-1356" title="Conditional GET" src="http://www.suryasuravarapu.com/wp-content/uploads/2011/01/condreq_GET_304.jpg" alt="" width="563" height="117" /></p>
<p>As far as implementation is concerned, relevant portion of the code is provided below:</p>
<p><script src="https://gist.github.com/774649.js?file=WebService1.scala"></script><noscript>[If you don't see the code embedded, here is the <a href="https://gist.github.com/774649#file_web_service1.scala">direct link</a>]</noscript><br />
<script src="https://gist.github.com/774649.js?file=XmlResponse.scala"></script><noscript>[If you don't see the code embedded, here is the <a href="https://gist.github.com/774649#file_xml_response.scala">direct link</a>]</noscript> </p>
<p>Value of <code>If-None-Match</code> header from the request is compared with the resource ETag value and then either respond with <code>304</code> (resource not modified) response or <code>200</code> (ok) response. Note that the value of <code>If-None-Match</code> can be an array of ETag values separated by commas, which is accounted for in the code above.  <code>NotModifiedResponse</code> used above can very well be a standard sub class of <a href="http://scala-tools.org/mvnsites/liftweb-2.2/framework/scaladocs/net/liftweb/http/LiftResponse.html">LiftResponse</a> in the framework. Regardless, you could create one as follows, which is actually a wrapper around Lift's <code>InMemoryResponse</code><br />
<script src="https://gist.github.com/774649.js?file=NotModifiedResponse.scala"></script><noscript>[If you don't see the code embedded, here is the <a href="https://gist.github.com/774649#file_not_modified_response.scala">direct link</a>]</noscript> </p>
<h3>Conditional PUT</h3>
<p>Conditional PUT is a great approach to enforce that the client is updating the most recent version of the resource state. Client does a GET first and gets the ETag value and uses that in the <code>If-Match</code> header (see below).  The usage of <code>If-Match</code> makes it a conditional request for updates. Server can enforce this by rejecting any updates without If-Match header in the request.</p>
<p>If the ETags match the resource state is updated. The server responds back with <code>204</code> (No Content) and with the new ETag value.</p>
<p><img class="alignnone size-full wp-image-1358" title="Conditional PUT 204" src="http://www.suryasuravarapu.com/wp-content/uploads/2011/01/condreq_PUT_204.jpg" alt="" width="562" height="184" /></p>
<p>Suppose some other client that doesn't have the updated ETag value tries to send a request to update. The server responds with <code>412</code> (Precondition Failed) with the new ETag header value (shown below)</p>
<p><img class="alignnone size-full wp-image-1359" title="Conditional PUT 412" src="http://www.suryasuravarapu.com/wp-content/uploads/2011/01/condreq_PUT_412.jpg" alt="" width="563" height="213" /></p>
<p>Implementation-wise, the code below compares the ETags and responds with either <code>204</code> or <code>412</code> indicating success or failure of conditional update (It also checks the request's content type and the existence of the resource and respond appropriately).</p>
<p><script src="https://gist.github.com/774649.js?file=gistfile5.scala"></script><noscript>[If you don't see the code embedded, here is the <a href="https://gist.github.com/774649#file_gistfile5.scala">direct link</a>]</noscript> </p>
<p>Just like in the case of GET, added <code>NoContentResponse</code> and <code>PreConditionFailedResponse</code>, both are wrappers around <code>InMemoryResponse</code>.</p>
<p><script src="https://gist.github.com/774649.js?file=gistfile6.scala"></script><noscript>[If you don't see the code embedded, here is the <a href="https://gist.github.com/774649#file_gistfile6.scala">direct link</a>]</noscript> </p>
<p>Complete source of the service is <a href="https://gist.github.com/777820">here</a>, just in case.</p>
<img src="http://feeds.feedburner.com/~r/SuryaSuravarapusBlog/~4/jjSfZIoyo8c" height="1" width="1"/>]]></content:encoded><description>ETag (or entity tag) values and/or Last modified time of the resource are typically used for this purpose. I'm only discussing ETags here, interchanging this with Last-modified time is trivial, so skipping. In this post I'm concentrating on deep ETags, where application developer can generate and compare ETags based on the underlying domain objects, database [...]</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://www.suryasuravarapu.com/2011/01/conditional-requests-with-lift.html/feed</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">4</slash:comments><feedburner:origLink>http://www.suryasuravarapu.com/2011/01/conditional-requests-with-lift.html</feedburner:origLink></item><item><title>Book Review: REST in Practice</title><link>http://feedproxy.google.com/~r/SuryaSuravarapusBlog/~3/pjawzeeyvGE/book-review-rest-in-practice.html</link><category>BookReview</category><category>REST</category><category>WebServices</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Surya Suravarapu</dc:creator><pubDate>Tue, 09 Nov 2010 04:22:15 PST</pubDate><guid isPermaLink="false">http://www.suryasuravarapu.com/?p=1297</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<h3><img style=' float: left; padding: 4px; margin: 0 7px 2px 0;'  class="alignleft" title="REST In Practice" src="http://suryasuravarapu.com/wp-content/uploads/2010/11/RESTInPractice.gif" alt="" width="144" height="189" />The Book</h3>
<p><strong>Title:</strong> REST in Practice (Hypermedia and Systems Architecture)</p>
<p><strong>Authors:</strong> Jim Webber, Savas Parastatidis, Ian Robinson</p>
<p><strong>Publisher:</strong> O'Reilly Media</p>
<h3>Review</h3>
<p>Couple of years ago, the authors of this book penned one of the finest articles explaining the principles of REST titled <a href="http://www.infoq.com/articles/webber-rest-workflow">How to GET a Cup of Coffee</a>. I was so thrilled when I first heard that the same authors are expanding the concepts into a book form! Now that the book is out and I finished reading it, here are some of my thoughts ...</p>
<p>This book covers a wide spectrum of ideas related to the RESTful systems including RPC-style systems, CRUD-based services, hypermedia systems, caching, Atom syndication and publishing protocol, security, and semantic web. The key is too see HTTP as an application-level protocol and not as a transport protocol. Start with that basic understanding, each chapter in the book deal with various integration challenges in the enterprise. Heart of this book is the focus towards building the systems in a web-centric way.</p>
<p>As the concepts evolve from chapter to chapter they are evaluated against the <a href="http://martinfowler.com/articles/richardsonMaturityModel.html">Richardson's maturity model</a>. At the base of the Richardson's model are the systems that use RPC-style (HTTP-as-transport-protocol) systems. The next level up, Level 1, are the systems that work in a resource-oriented model. Endpoints give way to thinking in terms of resources and URIs (e.g: OrderRequest end-point where a particular function on order is invoked vs. Order as a resource, example.org/order/1234).</p>
<p>Going up the pyramid, Level 2 maturity is attained by conforming to a uniform interface (HTTP verbs) and well-known HTTP response codes. There are many systems that claim to be RESTful but don't go beyond Level 2  (I don't want to sound pedantic, but just pointing out!). There are other articles and books with good details about Level 1 and Level 2 systems. If there is one take away from this book I have to say it's the understanding of the Level 3 of the maturity model, hypermedia systems. HATEOAS (Hypermedia as the Engine of the Application State) principle has been often discussed in various forums but perhaps not that well understood.</p>
<p>As with their InfoQ article, Restbucks, a coffee store web-application, is being built as the discussion proceeds from simple concepts to the more advanced ones. A domain that almost everyone can identify with, and puts the focus on the technical discussion rather than on the domain model intricacies. REST in practice, as the name suggests, takes the approach of implementing the concepts as they are discussed; Java and .NET are used in the book. Reading code is some times easier than understanding the abstract concepts, if you are like me.</p>
<p>Discussion on Atom and Atom publishing protocol is one of the best. If you don't have low latency (in micro seconds) requirement Atom format is the one that has to be given a good consideration while designing event-driven systems. In the penultimate chapter the authors compare Web services (SOAP and WS-* stack) with web-based (REST) systems. They compared both models in great length with respect to security, reliability, transaction management (including two-phase commits). A compelling read for anybody who is trying to get a hang of what these models offer.</p>
<p>Subbu Allamaraju's <a href="http://www.amazon.com/RESTful-Web-Services-Cookbook-ebook/dp/B0043D2ESQ/ref=dp_kinw_strp_1?ie=UTF8&amp;m=AG56TWVU5XWC2">RESTful Web Services Cookbook</a> is one of my favorites on the topic. I was fortunate enough to read the book during it's draft stage, which actually helped me immensely in understanding and reinforcing some of my concepts.  This book, REST in practice, helped me further in understanding more advanced topics like semantic web (RDF, OWL), and the event-driven system integration. I thoroughly enjoyed the book, and would certainly recommend for all REST enthusiasts (and doubters).</p>
<img src="http://feeds.feedburner.com/~r/SuryaSuravarapusBlog/~4/pjawzeeyvGE" height="1" width="1"/>]]></content:encoded><description>The Book Title: REST in Practice (Hypermedia and Systems Architecture) Authors: Jim Webber, Savas Parastatidis, Ian Robinson Publisher: O'Reilly Media Review Couple of years ago, the authors of this book penned one of the finest articles explaining the principles of REST titled How to GET a Cup of Coffee. I was so thrilled when I [...]</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://www.suryasuravarapu.com/2010/11/book-review-rest-in-practice.html/feed</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">1</slash:comments><feedburner:origLink>http://www.suryasuravarapu.com/2010/11/book-review-rest-in-practice.html</feedburner:origLink></item><item><title>JavaOne 2010 – My Impressions (Part 2)</title><link>http://feedproxy.google.com/~r/SuryaSuravarapusBlog/~3/yEEocuugTg4/javaone-2010-%e2%80%93-my-impressions-part-2.html</link><category>General</category><category>Conference</category><category>Lift</category><category>Scala</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Surya Suravarapu</dc:creator><pubDate>Thu, 30 Sep 2010 07:02:22 PDT</pubDate><guid isPermaLink="false">http://www.suryasuravarapu.com/?p=1268</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p><strong>Part 1 of the series is <a href="http://www.suryasuravarapu.com/2010/09/java-one-2010-my-impressions-part-1.html">here</a>.</strong></p>
<h3>Sessions (Contd.)</h3>
<p><strong>Building Real-Time Web Applications with Lift</strong></p>
<p>David  Pollak, founder of Lift (an open source) Scala-based web framework, did a  live demo building a chat application. I haven't seen many sessions (that I attended) in  the conference where the presenters did code demos. David pulled it  off without major glitches. He developed a comet-based chat application  along the way touching the concepts of Lift's templates, snippets and  Ajax support.</p>
<p>After the demo he went over some of the features of  Scala and Lift. Lift applications are secure by default, and he  mentioned that penetration testers are having tough time finding security  vulnerabilities in the application. Some of the factors that makes this  secure: Lift's forms mechanism associates randomly generated GUIDs with  form elements and functions. Risk of replay attacks is relatively low with Lift  applications. Lift builds all web pages as well formed XHTML rather than  a String or a stream of characters or bytes. Lift's SiteMap provides  unified menu generation and access control. All these and more actually  makes the developers life lot easy by having them concentrate on the  business logic of the domain and not on the underlying plumbing work.</p>
<p>Performance concerns with one of the applications built  on Rails caused Pollak to think about a Scala-based web application  utilizing the power of the JVM (which eventually improved the performance). Lift borrows a lot of  good ideas from Rails and other frameworks into Lift.</p>
<p>Foursquare and Novell Pulse are mentioned as publicly available apps that are built using Lift. There are many more startups and enterprise applications building interactive applications using the framework.</p>
<p><strong>Mint.com's Technology Behind the Scenes: Practical Lessons for Scalable Web Apps</strong></p>
<p>David Michaels and Daryl Puryear presented what turned out be one of my favorite sessions of the conference. Mint.com is world's largest free personal financial application with four million users covering 40K zip codes and all 50 states of the USA. Currently hosts 20 millions financial accounts with over 15K financial institutions.</p>
<p>The speakers went over step-by-step how they built the foundation of quality and security, and went over each of the other aspects of the pyramid: performance, scalability, manageability and maintainability. They traveled back in the time and shared the excitement and environment at the launch time some time in 2006/7 time frame. During that time they have a well-defined feature set but with unknown traffic. They wisely invested in production performance monitoring. Doing this enabled Mint to be proactive and enable fast triage of the issues. Monitored only the expensive operations to keep the overhead low. They decided to build a monitoring application (rather than buying) as they have some in-house expertise. Used Spring's auto-proxy feature. Aggregated results in memory and persist periodically. Simple interface was built on top to analyze the data.</p>
<p>Mint performed some performance tests and found that their database is the bottleneck (sounds familiar?). So they tuned the application code to reduce database usage. That brought only marginal improvement, and they hired services of an outside DB conultant who helped optimized the MySQL configuration, which ultimately removed the bottleneck. Lesson: small team can't have all expertise, hire consultants occasionally.</p>
<p>Traffic continued to grow, there were major spikes after press coverage. Once again database scaling was the need of the hour. They did horizontal scaling with multiple smaller databases. Shards are based on user and they made every user independent with no refs between the users. Non-user data is separated into logical databases (user lookup, shared data, monitoring data, user data).</p>
<p>Mint made continuous investments into beefing up security. Standard items were covered like data encryption, penetration testing, automated security scans, multiple DMZs and secure datacenter. Mint also took care of their application architecture so that a developer mistake will not result in a security hole.</p>
<p>Apart from that they have demoed an application they built for triaging errors in application logs, which was interesting. Mint is using XMLC as part of their frontend! Overall this is a very informative session not just from the technology standpoint but also to hear a startup's success story.</p>
<p><strong>Ninety-Seven Things Every Programmer Should Know</strong></p>
<p>Kevlin Henney and Kirk Pepperdine presented one of the entertaining sessions that I attended. Kevlin Henney in particular is an excellent speaker who knows how to present the message in an entertaining way.</p>
<p>If you haven't read this book yet, <a href="http://programmer.97things.oreilly.com/wiki/index.php/Contributions_Appearing_in_the_Book">here are those 97 things</a> appeared in the book. Speakers chose sixteen out of the list for the talk:</p>
<p>Ubuntu coding for your friends - Aslam Khan; Do lots of deliberate practice - Jon Jagger; Know your IDE - Heinz Kabutz; Put the mouse down and step away from the keyboard - Burk Hufnagel; Code reviews - Mattias Karlsson; Read code - Karianne Berg; Comment only what the code cannot say - Kevlin Henney; Code in the language of the domain - Dan North; Prefer domain-specific types to primitive types - Einar Landre; The road to performance is littered with dirty code bombs - Kirk Pepperdine; Interprocess communication affects application response time - Randy Stafford; The longevity of interim solutions - Klaus Marquardt; Two wrongs can make a right (and are difficult to fix) - Allan Kelly; Testing is the engineering rigor of software development - Neal Ford; Write tests for people - Gerard Meszaros; The boy scout rule - Uncle Bob</p>
<p>One of my favorites is <a href="http://programmer.97things.oreilly.com/wiki/index.php/The_Boy_Scout_Rule">the boy scout rule</a> interpretation for the code:</p>
<blockquote><p>Always check a module in cleaner than when you checked it out.</p></blockquote>
<p>This is one of those sessions that is difficult to summarize in a post like this. <a href="http://www.softdevtube.com/2010/08/23/97-things-every-programmer-should-know/">Checkout a video</a> from the speaker on the same topic but at a different venue.</p>
<p><strong>Simpler Scalability, Fault Tolerance, and Concurrency Through Actors and STM</strong></p>
<p>Akka is a tool that you should seriously cosider if you are writing applications with high concurrency needs. Jonas Bonér, the founder of Akka, presented the concepts pertaining to its software transactional model (STM), actors and persistence mechanism. I have recently started evaluating various concurrency models, and this presentation is exactly what I needed for some concrete guidance!</p>
<p>Actor model was popularized by Erlang which emerged in mid-80s. Actor model is a higher level abstraction, for the developers working on concurrent applications, dealing with the traditional locking and thread management. Actors do not share state with the other actors. Each actor has a mailbox and they can only interact with other actors by sending messages. All processing is done asynchronously, actors do not block so they are excellent candidates for event-based applications. Akka actors are extremely lightweight, you can create millions of them on a single workstation. Jonas Bonér discussed the Java API, Akka has also got a Scala API.</p>
<p>Akka's supervision model is inspired from Erlang. It goes by the "let it crash" approach implemented by linking actors. Akka's approach is that failures do happen, don't try to prevent them as they are inevitable. Your goal should be to make them fail soon and let a supervisor (who has a bigger picture) deal with it. A supervisor is an actor responsible for start, stop and monitoring child actors. Bonér discussed All-for-one (restart all the components that a supervisor is managing) and One-for-one (restart only the crashed actor) strategies.</p>
<p>STM model sees the memory as the transactional dataset. It can provide atomicty, consistency and isolation attributes to a transaction. Transactions are retried automatically after the collision. Akka STM is based on the ideas of Clojure STM, a compelling idea for providing transactional shared state. Akka also has pluggable storage backend currently supports Cassandra, MongoDB and Redis.</p>
<p>It is one of those sessions that I felt organizers saved the best for the last (day)!</p>
<img src="http://feeds.feedburner.com/~r/SuryaSuravarapusBlog/~4/yEEocuugTg4" height="1" width="1"/>]]></content:encoded><description>Part 1 of the series is here. Sessions (Contd.) Building Real-Time Web Applications with Lift David Pollak, founder of Lift (an open source) Scala-based web framework, did a live demo building a chat application. I haven't seen many sessions (that I attended) in the conference where the presenters did code demos. David pulled it off [...]</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://www.suryasuravarapu.com/2010/09/javaone-2010-%e2%80%93-my-impressions-part-2.html/feed</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">3</slash:comments><feedburner:origLink>http://www.suryasuravarapu.com/2010/09/javaone-2010-%e2%80%93-my-impressions-part-2.html</feedburner:origLink></item><item><title>JavaOne 2010 – My Impressions (Part 1)</title><link>http://feedproxy.google.com/~r/SuryaSuravarapusBlog/~3/t_R2df1uQsQ/java-one-2010-my-impressions-part-1.html</link><category>General</category><category>Conference</category><category>Java</category><category>NoSQL</category><category>REST</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Surya Suravarapu</dc:creator><pubDate>Wed, 29 Sep 2010 07:22:46 PDT</pubDate><guid isPermaLink="false">http://www.suryasuravarapu.com/?p=1255</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<h3>Bad</h3>
<p>Let's start with the bad and everything else would be an improvement when compared with that. Yes, food at the conference is awful. I thought that's only me who is looking out for vegetarian options, but apparently many people I knew who eat mostly anything under the Sun (no disrespect) are also equally disappointed. There is a huge scope for improvement in this area.</p>
<p>Some other aspects that need some attention -- it was a huge effort for the first couple of days to find the right conference room in Hilton and in Parc55; folks sitting towards the back couldn't see the slides that well because of the placement of the screen and projector; Poor wifi, worked intermittently. I hope Oracle considers moving Java One to Mascone in the future.</p>
<h3>Good</h3>
<p>Now that we put the worst behind us I will go to the other extreme and explain what's the best. Yes, there are some good sessions that I attended which I will go over in a minute. But the best part is meeting people and exchanging ideas. I got an opportunity to meet a whole lot of people I know for a while, worked with them online or exchanged tweets but got a chance to meetup for the first time. What more? I have even found a childhood friend whom I lost contact for the last few years!</p>
<h3>Sessions</h3>
<p>I will summarize some of the sessions that I liked at the conference (and skipping the ones that didn't appeal to me much):</p>
<p><strong>Script Bowl 2010: A Scripting Languages Shootout</strong></p>
<p>Clojure, Groovy, JRuby and Scala are the contending languages this time. They were presented by Rich Hickey, Graeme Rocher, Nick Sieger and Dick Wall respectively. Roberto Chinnici of Oracle acted as a judge/coordinator. Two rounds of presentations took place -- first round dealing with the language features and the second one presenting community features. Liked what I saw about <a href="http://docs.codehaus.org/display/GROOVY/2009/03/10/Meet+Spock!">Spock</a>.</p>
<p>It was all in a rapid fire mode as the time allotted is only one hour. I was actually thinking that to be a competition where a specific problem or two would be assigned to each person representing the language and then evaluate how each language approaches the problem. But apparently that's not the case.</p>
<p>The winner was announced based on the audience applause at the end, just for fun, I guess. Groovy topped followed by Scala as a close second.</p>
<p><strong>Advanced Java API for RESTful Web Services (JAX-RS)</strong></p>
<p>Paul Sandoz and Paul Chinnici started off with an overview of JAX-RS -- going over basic annotations (@Path, @Produces, etc.). Runtime resource resolution was dealt with in good detail. Middle part of the presentation was over integrating JAX-RS with EJBs and CDI (Yawn! I'm not much into it CDI).</p>
<p>Then they woke me up with some good discussion over content negotiation and conditional request support of JAX-RS. JAX-RS has got great content negotiation support covering media type, character set, language, and content encoding. Variant API is nice and flexible.</p>
<p>Equally nice is its support for conditional requests (GETs and PUTs) for caching representations and for concurrency control. They have demoed ETag validation and evaluatePrecondition flow.</p>
<p>"If you think you understand Java Generics than actually you don't understand it!" - a quote from the presenters that drew some laughs. The speakers went over how they had to deal with the type erasure issue and a work around of using GenericEntity to preserve type information at runtime. They finished the presentation discussing the pluggable exception handling mechanism of JAX-RS.</p>
<p>Overall, a nice presentation. I have expected them to discuss hypermedia support in Jersey but because of time constraint they couldn't get to it, as Paul Sandoz suggested after the talk when I asked him about it.</p>
<p><strong>The Next Big Java Virtual Machine Language (NBJL)</strong></p>
<p>Stephen Colebourne of OpenGamma is the speaker of this talk with potential controversy from the title itself. There are a lot of folks who swear by their language of choice, for what its worth, I thought it would be interesting to see what conclusion the presenter would arrive and based on what analysis. (There is also another section of people who completely denounce of the notion of NBJL. They consider polyglot programming is here to stay and there is not going to be one big successor, and you choose a language that best serves your task at hand. Let's leave that view point for another day!).</p>
<p>Colebourne defined what he thinks a next big language would be, one that's widely used (big job market) with supporting ecosystem and community. Examples: C, C++, Java, C#, Cobol, VB, Perl, PHP, Javascript, etc. So NBJL is one that challenges Java and eventually displaces it.</p>
<p>There are a lot of design decisions that were made at various points while Java was evolving. Many of them appeared to be right at that point and only after some experience people started to realize that there are better ways to approach. The speaker went over few items that are sore points in Java and what we have learnt from the real world experiences, from technology advancements, and from the other new breed of languages. Colebourne went over checked exceptions, primitives, arrays, 'everything is a monitor' concept, static methods, method overloading, and generics as some areas where NBJL could provide some solid alternatives.</p>
<p>Colebourne presented what can Java do to evolve still maintaining the "feel of Java". Bigger challenges for Java at this point are supporting -- Properties, Continuations, Control abstraction, Traits, Immutability, Design by Contract, and Reified generics. Another important point the speaker made was that the NBJL should be a "blue collar" language, a language of the masses. An average developer should be able to pick it up rather quickly and be productive in a <em>reasonable</em> time frame.</p>
<p>Towards that end the presenter looked at various languages: Clojure, Groovy, Scala, Fantom and discarded every one of them with some justification. Here is where it gets interesting. He concludes with a thought may be that Java should come up with a backward incompatible version and fix its warts. Regardless of how you respond to the concluding thought it was an excellent presentation overall covering a wide spectrum of concepts. If you are interested to hear from the presenter himself <a href="http://www.jroller.com/scolebourne/entry/the_next_big_jvm_language1">check this out</a>.</p>
<p><strong>NoSQL Alternatives: Principles and Patterns for Building Scalable Applications</strong></p>
<p>Nati Shalom of GigaSpaces presented data scalability patterns that emerged out of various NoSQL projects. He compared the new breed of technology against the traditional database scaling approach in terms of consistency, transaction and query semantics.</p>
<p>Some of the factors that are affecting the scalability needs -- social networks changed the web experience in the recent years. Read-mostly applications transformed into read/write and mostly predictable traffic has become a viral one with huge spikes at certain time intervals triggered by the events. SaaS model and cloud is mentioned as a factor. The speaker suggests that the economic downturn has forced the corporates to work efficiently, and no more that throwing more expensive hardware at the problem is an appealing solution.</p>
<p>Another factor that the speaker suggested was that the disk failures are up and lot higher than what are actually reported by the vendors (3% actual vs 0.5% reported). With the advancements in technology memory can be 100 - 1000x more efficient than the disk. RAMClouds become much more attractive for applications with high throughput requirements. New hardware makes it possible to store the entire set of data in-memory.</p>
<p>The presenter went over various alternatives: In-memory (GigaSpaces), Key/Value. Column (BigTable, HBase), Document model (CouchDB), Graph (Neo4J).  Shalom discussed common principles behind the NoSQL alternatives like - design for failure;  scale through partitioning of the data; maintain reliability through replication; provide flexibility between consistency, availability and partition failure; dynamic scaling. Some other principles (not so common) discussed are - document model support, SQL query support, MapReduce, transaction management, and security.</p>
<p>To be continued ...</p>
<p><strong>See <a href="http://www.suryasuravarapu.com/2010/09/javaone-2010-%e2%80%93-my-impressions-part-2.html">here for part 2</a> of the series.</strong></p>
<img src="http://feeds.feedburner.com/~r/SuryaSuravarapusBlog/~4/t_R2df1uQsQ" height="1" width="1"/>]]></content:encoded><description>Bad Let's start with the bad and everything else would be an improvement when compared with that. Yes, food at the conference is awful. I thought that's only me who is looking out for vegetarian options, but apparently many people I knew who eat mostly anything under the Sun (no disrespect) are also equally disappointed. [...]</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://www.suryasuravarapu.com/2010/09/java-one-2010-my-impressions-part-1.html/feed</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">1</slash:comments><feedburner:origLink>http://www.suryasuravarapu.com/2010/09/java-one-2010-my-impressions-part-1.html</feedburner:origLink></item><item><title>Lift and Content Negotiation</title><link>http://feedproxy.google.com/~r/SuryaSuravarapusBlog/~3/8S1-tIZ2EmM/lift-and-content-negotiation.html</link><category>REST</category><category>Scala</category><category>Lift</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Surya Suravarapu</dc:creator><pubDate>Thu, 19 Aug 2010 07:40:35 PDT</pubDate><guid isPermaLink="false">http://www.suryasuravarapu.com/?p=1229</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<h3>Overview</h3>
<p>This is a follow up of my <a href="http://www.suryasuravarapu.com/2010/08/lift-and-rest-uri-matching-and-content-negotiation.html">previous post on Lift and REST</a> discussing the aspects of URI matching and content negotiation. <a href="http://liftweb.net/">Lift</a> supports <code>Accept</code> header of HTTP by responding back with a representation in accordance with the media type provided in the header. However, it currently doesn't support <code>quality factor</code> (<code>q</code> parameter) of the <code>Accept</code> header, out of the box. Here  I will attempt to provide an approach to provide that support and along the way let's explore another compelling feature of the Lift's REST support.</p>
<h3>HTTP Accept Header</h3>
<p>Check <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">RFC 2616</a> for detailed explanation on <code>Accept</code> and other HTTP headers. Let's go over this based on an example: If a client sends an Accept header something like the following --</p>
<p><code>Accept: application/xml; q=0.8, application/json</code></p>
<p>is interpreted as: I prefer JSON representation but if you don't have it XML is my second choice.</p>
<p><code>Quality factor</code> or <code>q</code> parameter is the one that's used to specify the preference. <code>q</code> is a decimal ranging from 0.0 to 1.0 and is delimited with a semi-colon <code>(;)</code> following the media mime type. If no <code>q</code> parameter is specified it defaults to value of 1.0, indicating first among the options provided.</p>
<h3>Approach</h3>
<p>Before going into the approach for supporting the <code>q</code> parameter (for your Lift-based application) let's get into one of the things that you definitely want to see in a web framework: decouple business logic from the representation. Lift doesn't disappoint you in this area. In my case I was using the same business logic, authorizing the user and making the database lookups, returning the appropriate representation independent of the business logic.</p>
<p><code>serveJx</code> in <code>RestHelper</code> is there precisely for that purpose. Following code provides the URI matching rule (matches <code>/api/user/{user_id}</code> for GET requests) and returns an object that's of trait <code>Convertable</code>. Also, define an implicit def that converts the object to the appropriate representation (XML or JSON, in this case).</p>
<p><script src="http://gist.github.com/536539.js?file=gistfile4.scala"></script><noscript>[If you don't see the code embedded, here is the <a href="http://gist.github.com/536539.js?file=gistfile4.scala">direct link</a>]</noscript></p>
<p>Relevant pieces of <code>case class User</code> is provided below. If you are familiar with <a href="http://squeryl.org/">Squeryl</a> you may have already identified the annotations provided for the constructor arguments otherwise don't worry about it; Squeryl is an excellent Scala-based ORM (I like Squeryl quite a bit, that's a topic for another blog post!). <code>User</code> implements <code>Convertable</code>, meaning the two representations -- XML and JSON via <code>toXml</code> and <code>toJson</code> functions respectively. </p>
<p><script src="http://gist.github.com/536539.js?file=User.scala"></script><noscript>[If you don't see the code embedded, here is the <a href="http://gist.github.com/536539.js?file=User.scala">direct link</a>]</noscript></p>
<p>So with all the above in place, the following request would result in an XML or JSON response based on the <code>Accept</code> header. The logic for identifying the appropriate representation  is in the <code>RestHelper</code>'s <code>implicit def jxSel</code> shown below. As <code>RestHelper</code> does not support <code>q</code> parameter out of the box, <code>UserManagementService</code> extended from <code>RestHelper</code> changes the behavior by overriding <code>jxSel</code>. </p>
<p><script src="http://gist.github.com/536539.js?file=RestHelper.scala"></script><noscript>[If you don't see the code embedded, here is the <a href="http://gist.github.com/536539.js?file=RestHelper.scala">direct link</a>]</noscript></p>
<p><strong>Actual Parsing:</strong> Parsing of the Accept header and determining the representation is done using functions in the <code>ClientMediaPreference</code> object. Instead of embedding the code in this already lengthy post, here is a <a href="http://gist.github.com/536539#file_user_management_service.scala">link to the gist</a> covering the parsing logic.</p>
<h3>Conclusion</h3>
<p>There are a couple of areas that I still have to tighten-up the code, but that's the general idea. One of the <em>Todo</em> items is to send a <code>406 Not Acceptable</code> response if the representation that a client asks for is not implemented by the server.</p>
<p>Before closing, let's continue checking off another item from <a href="http://www.innoq.com/blog/st/2010/07/rest_litmus_test_for_web_frame.html">Tilkov's litmus test</a> (as we did in the <a href="http://www.suryasuravarapu.com/2010/08/lift-and-rest-uri-matching-and-content-negotiation.html">last post</a>) ...</p>
<blockquote><p>Can I easily use the same business logic while returning different content types in the response?</p></blockquote>
<p><strong>Answer:</strong> Yes, the framework is flexible in this aspect.</p>
<img src="http://feeds.feedburner.com/~r/SuryaSuravarapusBlog/~4/8S1-tIZ2EmM" height="1" width="1"/>]]></content:encoded><description>Overview This is a follow up of my previous post on Lift and REST discussing the aspects of URI matching and content negotiation. Lift supports Accept header of HTTP by responding back with a representation in accordance with the media type provided in the header. However, it currently doesn't support quality factor (q parameter) of [...]</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://www.suryasuravarapu.com/2010/08/lift-and-content-negotiation.html/feed</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">0</slash:comments><feedburner:origLink>http://www.suryasuravarapu.com/2010/08/lift-and-content-negotiation.html</feedburner:origLink></item><item><title>Lift and REST: URI Matching and Content Negotiation</title><link>http://feedproxy.google.com/~r/SuryaSuravarapusBlog/~3/6bAiG3WFvPc/lift-and-rest-uri-matching-and-content-negotiation.html</link><category>REST</category><category>Scala</category><category>Lift</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Surya Suravarapu</dc:creator><pubDate>Tue, 03 Aug 2010 08:15:13 PDT</pubDate><guid isPermaLink="false">http://www.suryasuravarapu.com/?p=1184</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>As a Scala enthusiast I'm currently evaluating<a href="http://liftweb.net/"> Lift</a>, particularly the aspect of its REST support. This could become a series of posts on the topic as I try to understand the framework better and may be subject it to a <a href="http://www.innoq.com/blog/st/2010/07/rest_litmus_test_for_web_frame.html">litmus test</a> proposed by Stefan Tilkov. Of course, I will not be making a judgment call whether the framework is RESTful or not as I don't want to get into a dogmatic discussion!</p>
<p>So far I like what I see, it is a productive framework with a nice set of features (and has cherry-picked some best ideas from other frameworks too), and what else it's Scala-based (my current favorite language).</p>
<h3>Setup</h3>
<p><a href="http://www.assembla.com/wiki/show/liftweb/Using_Maven">Getting started instructions</a> on Liftweb's wiki worked perfectly fine for me. I used instructions for Maven and I'm using Scala 2.8.</p>
<h3>URI Matching</h3>
<p><a href="http://main.scala-tools.org/mvnsites/liftweb-2.0/framework/scaladocs/net/liftweb/http/rest/RestHelper.html">RESTHelper</a> is the trait that you may want to extend for building your REST-based web services. Lift's URI dispatch follows the templating approach in which you would leave part of the URIs to be filled by the clients before they are submitted. For example, <code>id</code> can be sent dynamically by the user: <code>http://example.org/api/user/{id}</code></p>
<p>The following block of code can take care of the above URI matching ...</p>
<p><script src="http://gist.github.com/505507.js?file=gistfile1.scala"></script><noscript>Script disabled in your reader, <a href="http://gist.github.com/505507.js?file=gistfile1.scala">click here</a></noscript></p>
<p>the List of strings are the tokens after each "/" (forward slash) in the URI. The above code indicates that a GET request can handle that specific URI pattern. And when such a pattern is encountered invoke the method userDetails.  If a URI is encountered as <code>http://example.org/api/user/101</code>, <code>101</code> is bound to <code>id</code> variable.</p>
<p><code>Box[LiftResponse]</code> is the return type that's expected. Box goes by the same notion as Option in Scala. When you have stuff to return you would respond with <code>Full(LiftResponse)</code> and <code>Empty</code> when there is no response.  So here is an example of how you can URI match and dispatch for a sample CRUD (I'm using simple User account management).</p>
<p><script src="http://gist.github.com/505507.js?file=gistfile2.scala"></script><noscript>Script disabled in your reader, <a href="http://gist.github.com/505507.js?file=gistfile2.scala">click here</a></noscript></p>
<p>Ideally I would like to write this in a single case block without breaking into multiple units as I did above. When I add more than three case statements of this complexity (which is not that much, IMO) Scala compiler takes way too long and eventually gives up with an <code>OffsetTooBigException</code>. This <a href="https://lampsvn.epfl.ch/trac/scala/ticket/1133">issue is in bug tracker</a> for a while now, and the above approach of splitting the matchers into multiple units is based on the workaround suggested there.</p>
<p>The pattern matching is flexible and works great for multiple tokens too. Something like <code>http://example.org/user/{userId}/address/{addrId}</code> can be extracted using a very similar pattern like above with values for <code>userId</code> and <code>addrId</code> binding to their corresponding variables.</p>
<p><script src="http://gist.github.com/505507.js?file=gistfile3.scala"></script><noscript>Script disabled in your reader, <a href="http://gist.github.com/505507.js?file=gistfile3.scala">click here</a></noscript></p>
<p>Here is an excellent article on <a href="http://suereth.blogspot.com/2008/11/using-partial-functions-and-pattern.html">Scala's partial functions and pattern matching</a> that you may find it useful in the context of this discussion.</p>
<h3>Content Negotiation</h3>
<p><a href="http://en.wikipedia.org/wiki/Content_negotiation">Content negotiation</a> is one of the core concepts of RESTful systems where a client can indicate which media type(s) it prefers. Also within the media types it can specify the order of preference. Client does this by using <code>Accept</code> header. For example, consider the following <code>Accept</code> header --</p>
<p><code>Accept: application/xml;q=0.8, application/json;q=0.9</code></p>
<p>It indicates to the server a) it can accept XML and JSON formats and b) it prefers JSON over XML (by providing higher value for 'q' parameter. q value ranges from 0.0 to 1.0, higher value indicates more preference).</p>
<p>Ok, so how does Lift fares in this area? Mixed results --</p>
<ul>
<li>It recognizes which media type to serve by the Accept header. So for example <code>Accept:application/json</code> header from the client is matched to <code>case "api" :: "user" :: id :: _ XmlJson _ =&gt; ...</code></li>
<li>Similarly for XML, an accept header with <code>text/xml</code> is matched to <code>XmlGet</code> method fine. One issue that I encountered here is it only recognizes <code>text/xml</code> as XML media type and not <code>application/xml</code>. <code>application/xml</code> is actually preferable to <code>text/xml</code>, generally speaking. One reason on top of my head is text/* media types ignore the encoding specified in the content, in this case if you declare a specific encoding (e.g: UTF-8) in the XML declaration header it will be ignored.</li>
<li> It doesn't respect the q parameter value. So in the above example, <code>Accept: text/xml; q=0.8, application/json;q=0.9</code> it still serves the client XML as it only looks for if <code>text/xml</code> is present in the header.</li>
</ul>
<p>So let's look at Tilkov's first question in the list:</p>
<blockquote><p>Does the framework respect that an HTTP message does not only consist of  a URI? I.e., is dispatch done at least based on the HTTP verb, the URI,  the Content-type and Accept headers?</p></blockquote>
<p>My answer, at this point: Yes dispatch works great in terms of -- HTTP verb, the pattern matching URI templates and Accept headers (partially). Lift has to get its act together in further tightening its content negotiation support.</p>
<p>[I would love to contribute some patches for this and more (like hypermedia support, will elaborate it in the future posts). Lift folks, you have a volunteer here!]</p>
<p>Stay tuned!</p>
<p><strong>Update:</strong> Follow-up is posted here: <a href="http://www.suryasuravarapu.com/2010/08/lift-and-content-negotiation.html">Lift and Content Negotiation</a></p>
<img src="http://feeds.feedburner.com/~r/SuryaSuravarapusBlog/~4/6bAiG3WFvPc" height="1" width="1"/>]]></content:encoded><description>As a Scala enthusiast I'm currently evaluating Lift, particularly the aspect of its REST support. This could become a series of posts on the topic as I try to understand the framework better and may be subject it to a litmus test proposed by Stefan Tilkov. Of course, I will not be making a judgment [...]</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://www.suryasuravarapu.com/2010/08/lift-and-rest-uri-matching-and-content-negotiation.html/feed</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">9</slash:comments><feedburner:origLink>http://www.suryasuravarapu.com/2010/08/lift-and-rest-uri-matching-and-content-negotiation.html</feedburner:origLink></item><item><title>Spawning a Process from Hudson</title><link>http://feedproxy.google.com/~r/SuryaSuravarapusBlog/~3/0VYGZVL-8gI/spawning-a-process-from-hudson.html</link><category>Build</category><category>Tools</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Surya Suravarapu</dc:creator><pubDate>Fri, 02 Jul 2010 04:39:59 PDT</pubDate><guid isPermaLink="false">http://www.suryasuravarapu.com/?p=1170</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>It took a little while to figure this out, and hence documenting here ...</p>
<p>Need is to restart JBoss once the artifacts are deployed. I have two different jobs, one for building and deploying artifacts (EAR, in this case) and the other one to restart the server. Former invokes the latter as a part of its post-build actions.</p>
<p>I've setup a build step in <a href="http://hudson-ci.org/">Hudson</a> that executes a shell script which essentially invokes stop and start operations on the server. The server stops fine, but when I start the server in the background, server process gets killed once the Hudson process is finished. I've tried multiple ways of achieving this -- tried a couple of JBoss Maven plugins and tried Ant route too suspecting if that was an issue with my Shell script. But the real problem lies with the way Hudson deals with the spawned processes. This behavior is consistent with their design according to <a href="http://wiki.hudson-ci.org/display/HUDSON/Spawning+processes+from+build">Hudson docs</a>.</p>
<p>The suggested workaround for Unix systems is to use something like <a href="http://bmc.github.com/daemonize/">daemonize</a>. That didn't work for me. Daemonize works fine but the process is still being killed by the Hudson.  [Side note: daemonize is a neat tool, glad that I stumbled on it. Need it for some other purposes].</p>
<p>So how was this resolved? Searching the bug tracker, found the <a href="http://issues.hudson-ci.org/browse/HUDSON-3125">exact issue</a> that I mentioned here. The solution/workaround mentioned there works like a charm. Here is what it says --</p>
<blockquote><p>set the environment variable BUILD_ID to something like 'dontKillMe'  in the<br />
process that should stay alive.</p>
<p>Hudson looks for that environment variable when cleaning up stray  processes.</p></blockquote>
<p><img style=' float: left; padding: 4px; margin: 0 7px 2px 0;'  class="alignleft" title="Hudson-SetEnv-BUILD_ID" src="http://www.suryasuravarapu.com/wp-content/uploads/2010/07/SpawnProcessHudson.jpg" alt="" width="322" height="149" /></p>
<p>SetEnv plugin is already installed on my Hudson server, and setting BUILD_ID variable value worked! May be that Hudson could provide an option on the admin UI for the user to indicate not to kill the intentionally spawned processes.</p>
<img src="http://feeds.feedburner.com/~r/SuryaSuravarapusBlog/~4/0VYGZVL-8gI" height="1" width="1"/>]]></content:encoded><description>It took a little while to figure this out, and hence documenting here ... Need is to restart JBoss once the artifacts are deployed. I have two different jobs, one for building and deploying artifacts (EAR, in this case) and the other one to restart the server. Former invokes the latter as a part of [...]</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://www.suryasuravarapu.com/2010/07/spawning-a-process-from-hudson.html/feed</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">0</slash:comments><feedburner:origLink>http://www.suryasuravarapu.com/2010/07/spawning-a-process-from-hudson.html</feedburner:origLink></item><item><title>Terrastore Scala Client</title><link>http://feedproxy.google.com/~r/SuryaSuravarapusBlog/~3/0k51DczlILs/terrastore-scala-client.html</link><category>NoSQL</category><category>Scala</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Surya Suravarapu</dc:creator><pubDate>Tue, 01 Jun 2010 04:52:11 PDT</pubDate><guid isPermaLink="false">http://www.suryasuravarapu.com/?p=1156</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>For a while now, I've been an enthusiast following the <a href="http://en.wikipedia.org/wiki/NoSQL">NoSQL movement</a> and during the process drawn towards <a href="http://code.google.com/p/terrastore/">Terrastore</a>. Terrastore is based on <a href="http://www.terracotta.org/">Terracotta</a>, it's a modern document store which provides advanced  scalability and elasticity features without sacrificing consistency. If you haven't heard about Terrastore yet, it's worth checking out.</p>
<p>Sergio Bossa is spearheading the efforts on the project, and he is doing a terrific job at it. I've been in touch with Sergio for a bit and in discussions about how I can contribute to the project. Before jumping into the core aspects of the product I wanted to work on a client implementation so that I can play with Terrastore and understanding some of its intricacies. So I started working on a client implementation in Scala, my language of choice these days.</p>
<p>The client implementation is available at <a href="http://github.com/ssuravarapu/Terrastore-Scala-Client">Github</a>. There are few areas that I would like to tighten up a bit in the code, but it's out there for some early feedback.</p>
<p>I'm certainly excited to get started on the Terrastore core, and working with great minds -- Sergio and Greg Luck, a good friend and guru back from Ehcache days.</p>
<p>[Direct link to <a href="http://github.com/ssuravarapu/Terrastore-Scala-Client">Terrastore-Scala-Client</a> on Github]</p>
<img src="http://feeds.feedburner.com/~r/SuryaSuravarapusBlog/~4/0k51DczlILs" height="1" width="1"/>]]></content:encoded><description>For a while now, I've been an enthusiast following the NoSQL movement and during the process drawn towards Terrastore. Terrastore is based on Terracotta, it's a modern document store which provides advanced scalability and elasticity features without sacrificing consistency. If you haven't heard about Terrastore yet, it's worth checking out. Sergio Bossa is spearheading the [...]</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://www.suryasuravarapu.com/2010/06/terrastore-scala-client.html/feed</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">2</slash:comments><feedburner:origLink>http://www.suryasuravarapu.com/2010/06/terrastore-scala-client.html</feedburner:origLink></item><media:rating>nonadult</media:rating></channel></rss>
