<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Zach&#039;s Blog</title>
	<atom:link href="http://zcox.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://zcox.wordpress.com</link>
	<description>Just another WordPress.com weblog</description>
	<lastBuildDate>Tue, 01 Nov 2011 16:50:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='zcox.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Zach&#039;s Blog</title>
		<link>http://zcox.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://zcox.wordpress.com/osd.xml" title="Zach&#039;s Blog" />
	<atom:link rel='hub' href='http://zcox.wordpress.com/?pushpress=hub'/>
		<item>
		<title>The Power of Programmatic Builds</title>
		<link>http://zcox.wordpress.com/2011/10/24/the-power-of-programmatic-builds/</link>
		<comments>http://zcox.wordpress.com/2011/10/24/the-power-of-programmatic-builds/#comments</comments>
		<pubDate>Mon, 24 Oct 2011 15:12:00 +0000</pubDate>
		<dc:creator>Zach Cox</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[sbt]]></category>

		<guid isPermaLink="false">http://zcox.wordpress.com/?p=265</guid>
		<description><![CDATA[Using a build tool that provides the full power of a real programming language makes many tasks much easier than build tools that use a declarative markup language. To cut to the chase, I&#8217;m referring to sbt vs Maven (or Ant). Just wanted to write a quick post that shows how we have customized our [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=zcox.wordpress.com&amp;blog=8766317&amp;post=265&amp;subd=zcox&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Using a build tool that provides the full power of a real programming language makes many tasks much easier than build tools that use a declarative markup language. To cut to the chase, I&#8217;m referring to <a href="http://code.google.com/p/simple-build-tool/wiki/DocumentationHome">sbt</a> vs <a href="http://maven.apache.org/">Maven</a> (or <a href="http://ant.apache.org/">Ant</a>). Just wanted to write a quick post that shows how <a href="http://pongr.com">we</a> have customized our sbt builds in two important ways: using different versions of dependencies based on which version of Scala we&#8217;re using, and publishing to different snapshot and release repositories depending on the project&#8217;s current version.</p>
<p>In the land of Scala, it&#8217;s common to publish library jars compiled with multiple versions of Scala (<a href="http://www.google.com/search?q=scala+backwards+incompatibility">long story</a>). So sbt supports <a href="http://code.google.com/p/simple-build-tool/wiki/CrossBuild">cross-building</a>. In this project&#8217;s build.properties file, we specify to compile it with both Scala 2.9.1 and 2.8.1:</p>
<pre class="brush: plain;">
build.scala.versions=2.9.1 2.8.1
</pre>
<p>That&#8217;s great and all, but one of the dependencies we want to use, <a href="http://code.google.com/p/specs/">Specs</a>, only goes up to version <a href="http://scala-tools.org/repo-releases/org/scala-tools/testing/specs_2.8.1/1.6.8/specs_2.8.1-1.6.8.pom">1.6.8</a> with Scala 2.8.1, then switches to version <a href="http://scala-tools.org/repo-releases/org/scala-tools/testing/specs_2.9.1/1.6.9/specs_2.9.1-1.6.9.pom">1.6.9</a> for Scala 2.9.1. Might seem like a problem, but because we define our build in Scala, we just throw in an if-statement:</p>
<pre class="brush: scala;">
class Project(info: ProjectInfo) extends DefaultProject(info) {
  //specs version depends on Scala version
  val specsVersion = if (&quot;2.9.1&quot; == buildScalaVersion) &quot;1.6.9&quot; else &quot;1.6.8&quot;
  val specs = &quot;org.scala-tools.testing&quot; %% &quot;specs&quot; % specsVersion % &quot;test&quot;
}
</pre>
<p>Run +update on that and you&#8217;ll get Specs 1.6.8 for Scala 2.8.1 and Specs 1.6.9 for Scala 2.9.1.</p>
<p>It&#8217;s standard practice to use separate Maven repositories for snapshot versions and release versions. Case in point: scala-tools <a href="http://scala-tools.org/repo-snapshots/">snapshot</a> &amp; <a href="http://scala-tools.org/repo-releases/">release</a> repos. When your project is at version 0.9-SNAPSHOT you should publish its jars to the snapshot repo. Then when version 0.9 is released, publish to the release repo.</p>
<p>Again, because we&#8217;re defining the build in Scala, we just do some programming to set this up exactly how we want it:</p>
<pre class="brush: scala;">
class Project(info: ProjectInfo) extends DefaultProject(info) {
  //publish destination depends on build version
  override def managedStyle = ManagedStyle.Maven
  def suffix = if (version.toString endsWith &quot;-SNAPSHOT&quot;) &quot;snapshots/&quot; else &quot;releases/&quot;
  val publishTo = &quot;Scala Tools Nexus&quot; at &quot;http://nexus.scala-tools.org/content/repositories/&quot; + suffix
  Credentials(Path.userHome / &quot;.ivy2&quot; / &quot;.scala_tools_credentials&quot;, log)
}
</pre>
<p>Pretty simple examples, but the point is that we&#8217;re not locked in to the XML elements &amp; attributes that some Maven plugin author exposed to us. With sbt we can do basically whatever we need to in the build file to customize our build to meet project requirements.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/zcox.wordpress.com/265/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/zcox.wordpress.com/265/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/zcox.wordpress.com/265/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/zcox.wordpress.com/265/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/zcox.wordpress.com/265/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/zcox.wordpress.com/265/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/zcox.wordpress.com/265/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/zcox.wordpress.com/265/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/zcox.wordpress.com/265/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/zcox.wordpress.com/265/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/zcox.wordpress.com/265/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/zcox.wordpress.com/265/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/zcox.wordpress.com/265/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/zcox.wordpress.com/265/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=zcox.wordpress.com&amp;blog=8766317&amp;post=265&amp;subd=zcox&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://zcox.wordpress.com/2011/10/24/the-power-of-programmatic-builds/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/acc13d0a0206b114de1590b2e0193426?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Zach</media:title>
		</media:content>
	</item>
		<item>
		<title>Database Actors in Lift</title>
		<link>http://zcox.wordpress.com/2011/01/18/database-actors-in-lift/</link>
		<comments>http://zcox.wordpress.com/2011/01/18/database-actors-in-lift/#comments</comments>
		<pubDate>Tue, 18 Jan 2011 21:42:55 +0000</pubDate>
		<dc:creator>Zach Cox</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[actor]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[lift]]></category>
		<category><![CDATA[transaction]]></category>

		<guid isPermaLink="false">http://zcox.wordpress.com/?p=234</guid>
		<description><![CDATA[We&#8217;ve been slowly migrating our Lift web app to more of an event-driven architecture. This approach offloads non-essential processing out of the HTTP request/response cycle into actors, and makes things a lot more flexible on the back-end. However, as we&#8217;ve discovered during this process, there are several things to be aware of by doing database [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=zcox.wordpress.com&amp;blog=8766317&amp;post=234&amp;subd=zcox&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>We&#8217;ve been slowly migrating our <a href="http://liftweb.net">Lift</a> web app to more of an <a href="http://www.google.com/search?q=event+driven+architecture">event-driven architecture</a>.  This approach offloads non-essential processing out of the HTTP request/response cycle into actors, and makes things a lot more flexible on the back-end.  However, as we&#8217;ve discovered during this process, there are several things to be aware of by doing database processing in actors.  In this post we&#8217;ll examine those problems and present our current solution, which is also <a href="https://github.com/zcox/lift-db-actor">demonstrated in an example Lift app</a> and was recently <a href="http://groups.google.com/group/liftweb/browse_thread/thread/c65d93e1b9d4f395">discussed on the Lift mailing list</a>.</p>
<h3>Background</h3>
<p>The app is very simple: users say things and these quotes show up on the home page. Other users can then &#8220;like&#8221; the quotes.  The most-liked quotes are also shown on the home page.</p>
<p><a href="http://zcox.files.wordpress.com/2011/01/quotes.png"><img src="http://zcox.files.wordpress.com/2011/01/quotes.png?w=283&#038;h=300" alt="" title="quotes" width="283" height="300" class="alignnone size-medium wp-image-244" /></a></p>
<p>Let&#8217;s take a look at the Like link in more detail.  When you click it, a function in a <a href="https://github.com/zcox/lift-db-actor/blob/master/src/main/scala/code/snippet/Quotes.scala">snippet</a> runs on the server-side.</p>
<p><a href="http://zcox.files.wordpress.com/2011/01/quote.png"><img src="http://zcox.files.wordpress.com/2011/01/quote.png?w=300&#038;h=159" alt="A quote" title="quote" width="300" height="159" class="alignnone size-medium wp-image-242" /></a></p>
<p>This function toggles the like status between a Quote and a User.  So after you like a quote, the link changes to Unlike so you can take back your like.</p>
<pre class="brush: scala; highlight: [3];">
    def likeLink(q: Quote): NodeSeq = a(likeLinkText(q), &quot;id&quot; -&gt; likeLinkId(q)) {
      for (u &lt;- User.currentUser)
        u toggle q
      Replace(likeLinkId(q), likeLink(q))
    }
</pre>
<p>This toggling makes its way to the <a href="https://github.com/zcox/lift-db-actor/blob/master/src/main/scala/code/model/QuoteLike.scala">QuoteLike</a> meta mapper, to either the like or unlike method.  In both cases, after the action is processed we send a message to the <a href="https://github.com/zcox/lift-db-actor/blob/master/src/main/scala/code/actor/QuotePopularity.scala">QuotePopularity</a> actor.</p>
<pre class="brush: scala; highlight: [7,16];">
object QuoteLike extends QuoteLike with LongKeyedMetaMapper[QuoteLike] with Logger {
...
  def like(u: User, q: Quote) =
    if (!exists_?(u, q)) {
      val ql = QuoteLike.create.user(u).quote(q).saveMe
      debug(&quot;User &quot; + u.id.is + &quot; liked Quote &quot; + q.id.is)
      QuotePopularity !&lt;&gt; q
      Full(ql)
    } else
      Empty

  def unlike(u: User, q: Quote) =
    for (ql &lt;- find(u, q)) {
      ql.delete_!
      debug(&quot;User &quot; + u.id.is + &quot; unliked Quote &quot; + q.id.is)
      QuotePopularity !&lt;&gt; q
    }

  def toggle(u: User, q: Quote) = if (exists_?(u, q)) unlike(u, q) else like(u, q)
}
</pre>
<p>This actor updates that quote&#8217;s popularity.  The Popular Quotes section on the <a href="https://github.com/zcox/lift-db-actor/blob/master/src/main/webapp/index.html">home page</a> renders the top 10 quotes by descending popularity.</p>
<pre class="brush: scala;">
object QuotePopularity extends DbActor with Logger {
  protected def messageHandler = {
    case q: Quote =&gt;
      val p = q.likeCount
      q.popularity(p).save
      debug(&quot;Quote &quot; + q.id.is + &quot; popularity = &quot; + p)
  }
}
</pre>
<p>While we could easily have done this update in the QuoteLike like and unlike methods, we chose to offload this processing to an actor, since it is not essential to the AJAX response after the user clicks the Like/Unlike link.  It&#8217;s a simple calculation in this example app, but imagine a more complex app where a lot of number-crunching must take place to determine trending items (*cough*<a href="http://www.pongr.com">Pongr</a>*ahem*). We don&#8217;t want the AJAX response delayed, so we let an actor update the popularity sometime later.  And the popularity of quotes is then updated &amp; cached for the next home page load.</p>
<h3>Problem</h3>
<p>While this is a very common use case for actors (asynchronous &#8220;later&#8221; processing), what&#8217;s not immediately obvious is the dreaded <em>database transaction</em>.  It&#8217;s standard in Lift to wrap every HTTP request inside a transaction.  This is configured in <a href="https://github.com/zcox/lift-db-actor/blob/master/src/main/scala/bootstrap/liftweb/Boot.scala">Boot</a>:</p>
<pre class="brush: scala;">
S.addAround(DB.buildLoanWrapper)
</pre>
<p>So at the end of our AJAX HTTP req/resp cycle due to the user clicking the Like/Unlike link, the new (or deleted) QuoteLike object is committed to the database, and can be read by other parts of our app.  So far, so good.</p>
<p>However, by default, Lift actors are <em>not</em> wrapped in database transactions.  So as soon as you send that message to the QuotePopularity actor, it may start updating the quote&#8217;s popularity.  We have no guarantees as to when that actor will execute; it may be immediately in which case it won&#8217;t see the new/deleted QuoteLike, or it may happen to be after the QuoteLike is committed.  </p>
<p>Another problem occurs if this actor makes changes to the database itself.  Since it&#8217;s executing outside of a transaction, these changes are committed immediately, leaving some partially updated entities open to discovery by other parts of the app.  Definitely not something we want to happen.</p>
<h3>Solution</h3>
<p>Our approach to solving this problem is the following simple <a href="https://github.com/zcox/lift-db-actor/blob/master/src/main/scala/code/actor/DbActor.scala">DbActor</a> trait:</p>
<pre class="brush: scala;">
trait DbActor extends LiftActor {
  override protected def aroundLoans = List(DB.buildLoanWrapper)

  def !&lt;&gt;(msg: Any): Unit = DB.performPostCommit { this ! msg }
}
</pre>
<p>We now follow these two best practices for actors that use the database:</p>
<ol>
<li>Extend DbActor instead of LiftActor</li>
<li>Only send messages to the actor using the !&lt;&gt; method</li>
</ol>
<p>So #1 ensures that this actor&#8217;s messageHandler method is executed inside a transaction.  LiftActor has this awesome aroundLoans method, where we can simply wrap the actor in a DB.buildLoanWrapper (just like HTTP requests).  Database changes made by the actor will now all be committed when the actor is finished.  Our QuotePopularity actor above extends DbActor.  Actors executing inside database transactions: <em>check</em>.</p>
<p>The !&lt;&gt; method in #2 ensures that this actor will only execute after the current database transaction commits.  Again, Lift comes to the rescue with the DB.performPostCommit method, which does exactly what we want.  So the QuotePopularity actor above will only execute after the AJAX HTTP request that creates/deletes a QuoteLike has been committed to the database.  This way, we know for sure that the QuotePopularity actor will see the QuoteLike changes.  Actors executing after the current transaction commits: <em>check</em>.</p>
<h3>Conclusion</h3>
<p>So just remember: if your Lift actor does anything with the database, follow the two best practices above.  Wrap actor execution in a transaction, and send messages to the actor so that the actor executes after the current transaction commits.</p>
<p>It&#8217;s worth pointing out that we&#8217;re hard-coding the notification of the QuotePopularity actor above in the like and unlike methods.  This is OK, but a better solution would be a generic pub-sub event system, where those methods would publish &#8220;quote liked/unliked&#8221; events, and QuotePopularity would just subscribe to those events.  Similarly, QuotePopularity could publish a &#8220;quote popularity updated&#8221; event when it&#8217;s done, and something else like a comet actor could receive that event and update the Popular Quotes section of the home page.  But that&#8217;s a topic for another blog post&#8230;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/zcox.wordpress.com/234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/zcox.wordpress.com/234/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/zcox.wordpress.com/234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/zcox.wordpress.com/234/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/zcox.wordpress.com/234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/zcox.wordpress.com/234/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/zcox.wordpress.com/234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/zcox.wordpress.com/234/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/zcox.wordpress.com/234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/zcox.wordpress.com/234/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/zcox.wordpress.com/234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/zcox.wordpress.com/234/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/zcox.wordpress.com/234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/zcox.wordpress.com/234/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=zcox.wordpress.com&amp;blog=8766317&amp;post=234&amp;subd=zcox&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://zcox.wordpress.com/2011/01/18/database-actors-in-lift/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/acc13d0a0206b114de1590b2e0193426?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Zach</media:title>
		</media:content>

		<media:content url="http://zcox.files.wordpress.com/2011/01/quotes.png?w=283" medium="image">
			<media:title type="html">quotes</media:title>
		</media:content>

		<media:content url="http://zcox.files.wordpress.com/2011/01/quote.png?w=300" medium="image">
			<media:title type="html">quote</media:title>
		</media:content>
	</item>
		<item>
		<title>Lift + Ostrich</title>
		<link>http://zcox.wordpress.com/2010/12/13/lift-ostrich/</link>
		<comments>http://zcox.wordpress.com/2010/12/13/lift-ostrich/#comments</comments>
		<pubDate>Mon, 13 Dec 2010 22:27:20 +0000</pubDate>
		<dc:creator>Zach Cox</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[lift]]></category>
		<category><![CDATA[ostrich]]></category>

		<guid isPermaLink="false">http://zcox.wordpress.com/?p=194</guid>
		<description><![CDATA[We&#8217;ve been doing some profiling on http://pongr.com recently and have started using Ostrich.  Our site uses Lift and I thought I&#8217;d put together a brief tutorial showing how to use Ostrich in a Lift-based web app.  Our approach was heavily inspired by the usage of Ostrich in ESME, is described below and is available on [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=zcox.wordpress.com&amp;blog=8766317&amp;post=194&amp;subd=zcox&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>We&#8217;ve been doing some profiling on <a href="http://pongr.com">http://pongr.com</a> recently and have started using <a href="https://github.com/maw/ostrich">Ostrich</a>.  Our site uses <a href="http://liftweb.net">Lift</a> and I thought I&#8217;d put together a brief tutorial showing how to use Ostrich in a Lift-based web app.  Our approach was heavily inspired by the <a href="http://groups.google.com/group/liftweb/browse_thread/thread/b6f836b5b8ee5371/800bacefed3f7659">usage of Ostrich in ESME</a>, is described below and is <a href="https://github.com/zcox/lift_21_sbt-ostrich">available on Github</a>.</p>
<p>In this example we&#8217;ll use Lift 2.1 and Ostrich 2.2.10.  <strong>Update:</strong> As Steve commented, there is a newer release of Ostrich (<a href="http://maven.twttr.com/com/twitter/ostrich/2.3.3/ostrich-2.3.3.pom">2.3.3</a> as of this post) but it requires Scala 2.8.1, so to use it you would also need to use Lift 2.2.  You&#8217;d also need to add the <a href="http://maven.twttr.com">Twitter maven repo</a> to the sbt project.</p>
<h3>Setup</h3>
<p>First off, we need to add the JBoss maven repo and the Ostrich dependency to the <a href="https://github.com/zcox/lift_21_sbt-ostrich/blob/master/project/build/LiftProject.scala">sbt project</a>:</p>
<pre class="brush: scala; highlight: [1,10];">

val jbossRepo = &quot;jboss&quot; at &quot;http://repository.jboss.org/nexus/content/groups/public/&quot;

override def libraryDependencies = Set(
  &quot;net.liftweb&quot; %% &quot;lift-webkit&quot; % liftVersion % &quot;compile-&gt;default&quot;,
  &quot;net.liftweb&quot; %% &quot;lift-mapper&quot; % liftVersion % &quot;compile-&gt;default&quot;,
  &quot;org.mortbay.jetty&quot; % &quot;jetty&quot; % &quot;6.1.22&quot; % &quot;test-&gt;default&quot;,
  &quot;junit&quot; % &quot;junit&quot; % &quot;4.5&quot; % &quot;test-&gt;default&quot;,
  &quot;org.scala-tools.testing&quot; %% &quot;specs&quot; % &quot;1.6.5&quot; % &quot;test-&gt;default&quot;,
  &quot;com.h2database&quot; % &quot;h2&quot; % &quot;1.2.138&quot;,
  &quot;com.twitter&quot; % &quot;ostrich_2.8.0&quot; % &quot;2.2.10&quot;
  ) ++ super.libraryDependencies
</pre>
<p>Ostrich will provide stats via HTTP, so we need to define the port it will use in <a href="https://github.com/zcox/lift_21_sbt-ostrich/blob/master/src/main/resources/props/default.props">default.props</a>:</p>
<pre class="brush: plain;">

#Enable and set port for Ostrich web access (JSON output)
admin_http_port=9990
</pre>
<p>Ostrich needs to be started when the web app <a href="https://github.com/zcox/lift_21_sbt-ostrich/blob/master/src/main/scala/bootstrap/liftweb/Boot.scala">boots up</a>:</p>
<pre class="brush: scala;">

// Ostrich setup
val runtime = new RuntimeEnvironment(getClass)
val config = new Config
config(&quot;admin_http_port&quot;) = Props.getInt(&quot;admin_http_port&quot;) openOr 9990
ServiceTracker.startAdmin(config, runtime)
</pre>
<p>As far as configuration goes, that&#8217;s it!  Ostrich is now ready to collect data and provide stats.</p>
<h3>Counters</h3>
<p>The first type of data we&#8217;ll collect is the count of something.  Could be number of users registered, number of new blog posts, etc.  For this example we&#8217;ll count each time the <a href="https://github.com/zcox/lift_21_sbt-ostrich/blob/master/src/main/scala/code/snippet/HelloWorld.scala">HelloWorld.howdy snippet</a> is rendered:</p>
<pre class="brush: scala; highlight: [2];">

def howdy(in: NodeSeq): NodeSeq = {
  Stats.incr(&quot;howdy-renders&quot;)
  Helpers.bind(&quot;b&quot;, in, &quot;time&quot; -&gt; date.map(d =&gt; Text(d.toString)))
}
</pre>
<h3>Gauges</h3>
<p>A gauge is just some value of something at a particular point in time, perhaps a measurement from a sensor or some calculated value.  In our example we&#8217;ll use WTFs/min:</p>
<pre class="brush: scala;">

import scala.math._
Stats.makeGauge(&quot;wtfs-per-min&quot;) { rint(random * 10) }
</pre>
<p>We set up this particular gauge in <a href="https://github.com/zcox/lift_21_sbt-ostrich/blob/master/src/main/scala/bootstrap/liftweb/Boot.scala">Boot.scala</a> and just generate random data.  You just name a gauge and provide a function that always returns the current value.</p>
<h3>Timings</h3>
<p>Ostrich can also record how long it takes to execute certain blocks of code.  Simply wrap the code you want to time in a call to Stats.time.  For extra convenience, it will return whatever your code block returns.</p>
<p>In this example, we suspect our <a href="https://github.com/zcox/lift_21_sbt-ostrich/blob/master/src/main/scala/code/snippet/HelloWorld.scala">important number calculation</a> is slowing down page loads, so we&#8217;ll time it:</p>
<pre class="brush: scala; highlight: [2];">

def importantNumber(in: NodeSeq): NodeSeq = {
  val n = Stats.time(&quot;important-number-calculation&quot;) {
    import scala.math._
    Thread.sleep(round(2000*random + 1000))
    7
  }
  &lt;span&gt;{n}&lt;/span&gt;
}
</pre>
<h3>Stats</h3>
<p>Now that we&#8217;re collecting all three types of data, let&#8217;s pull some stats from Ostrich.  After loading our home page at <a href="http://localhost:8080">http://localhost:8080</a> several times, we can get the latest stats from <a href="http://localhost:9990/stats">http://localhost:9990/stats</a>.</p>
<pre class="brush: jscript;">
{&quot;counters&quot;:{&quot;howdy-renders&quot;:7},&quot;timings&quot;:{&quot;important-number-calculation&quot;:{&quot;count&quot;:7,&quot;standard_deviation&quot;:621,&quot;p75&quot;:3405,&quot;histogram&quot;:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],&quot;maximum&quot;:2878,&quot;p9999&quot;:3405,&quot;p90&quot;:3405,&quot;p25&quot;:2015,&quot;p99&quot;:3405,&quot;average&quot;:2179,&quot;minimum&quot;:1447,&quot;p50&quot;:2619,&quot;p999&quot;:3405}},&quot;jvm&quot;:{&quot;nonheap_committed&quot;:46530560,&quot;heap_max&quot;:1908932608,&quot;thread_peak_count&quot;:54,&quot;heap_committed&quot;:120782848,&quot;uptime&quot;:436119,&quot;nonheap_max&quot;:224395264,&quot;thread_daemon_count&quot;:12,&quot;num_cpus&quot;:8,&quot;thread_count&quot;:54,&quot;nonheap_used&quot;:45256464,&quot;start_time&quot;:1292277570344,&quot;heap_used&quot;:9656904},&quot;gauges&quot;:{&quot;wtfs-per-min&quot;:5.0}}
</pre>
<p>By default, Ostrich returns stats in JSON format which is great for parsing for display in another app or viewing with <a href="https://addons.mozilla.org/af/firefox/addon/10869/">JSONView</a>.  However, for this blog post perhaps the plaintext version at <a href="http://localhost:9990/stats.txt">http://localhost:9990/stats.txt</a> is more readable:</p>
<pre class="brush: plain;">
counters:
  howdy-renders: 7
gauges:
  wtfs-per-min: 2.0
jvm:
  heap_committed: 120782848
  heap_max: 1908932608
  heap_used: 8911680
  nonheap_committed: 46530560
  nonheap_max: 224395264
  nonheap_used: 45252880
  num_cpus: 8
  start_time: 1292277570344
  thread_count: 54
  thread_daemon_count: 12
  thread_peak_count: 54
  uptime: 430468
timings:
  important-number-calculation: (average=2179, count=7, maximum=2878, minimum=1447, p25=2015, p50=2619, p75=3405, p90=3405, p99=3405, p999=3405, p9999=3405, standard_deviation=621)
</pre>
<p>We can see that the howdy snippet was rendered 7 times and we&#8217;re currently seeing 2 WTFs/min.  We also have collected 7 timings for the important number calculation and we see various stats like min/max/avg, etc.  Now we know precisely how much time is being spent calculating important numbers, and we can choose to optimize if needed.</p>
<p>While not as detailed or comprehensive as a profiling tool like <a href="https://visualvm.dev.java.net/">VisualVM</a>, Ostrich is a great, simple tool for collecting performance data in specific parts of your Scala app.  And integration with Lift really could not be easier.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/zcox.wordpress.com/194/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/zcox.wordpress.com/194/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/zcox.wordpress.com/194/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/zcox.wordpress.com/194/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/zcox.wordpress.com/194/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/zcox.wordpress.com/194/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/zcox.wordpress.com/194/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/zcox.wordpress.com/194/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/zcox.wordpress.com/194/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/zcox.wordpress.com/194/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/zcox.wordpress.com/194/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/zcox.wordpress.com/194/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/zcox.wordpress.com/194/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/zcox.wordpress.com/194/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=zcox.wordpress.com&amp;blog=8766317&amp;post=194&amp;subd=zcox&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://zcox.wordpress.com/2010/12/13/lift-ostrich/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/acc13d0a0206b114de1590b2e0193426?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Zach</media:title>
		</media:content>
	</item>
		<item>
		<title>Jersey + Guice + Scala</title>
		<link>http://zcox.wordpress.com/2009/09/22/jersey-guice-scala/</link>
		<comments>http://zcox.wordpress.com/2009/09/22/jersey-guice-scala/#comments</comments>
		<pubDate>Wed, 23 Sep 2009 02:03:59 +0000</pubDate>
		<dc:creator>Zach Cox</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[guice]]></category>
		<category><![CDATA[jersey]]></category>
		<category><![CDATA[jetty]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[restful]]></category>

		<guid isPermaLink="false">http://zcox.wordpress.com/?p=179</guid>
		<description><![CDATA[At Pongr, our RESTful web services are built using Jersey, Guice and Scala (among many other technologies). Here&#8217;s a quick post that shows how to set up an example project that uses all three. By the end we&#8217;ll be able to declare Guice bindings in our own custom module and have them injected into Jersey [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=zcox.wordpress.com&amp;blog=8766317&amp;post=179&amp;subd=zcox&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>At <a href="http://www.pongr.com">Pongr</a>, our RESTful web services are built using <a href="https://jersey.dev.java.net/">Jersey</a>, <a href="http://code.google.com/p/google-guice/">Guice</a> and <a href="http://code.google.com/p/google-guice/">Scala</a> (among many other technologies).  Here&#8217;s a quick post that shows how to set up an example project that uses all three.  By the end we&#8217;ll be able to declare Guice bindings in our own custom module and have them injected into Jersey resource classes.</p>
<p>We&#8217;ll manage everything with <a href="http://maven.apache.org/">Maven</a>, so first create your pom.xml.  I know it looks like a lot, but only has three Jersey dependencies (and one on the Servlet 2.5 API to make things compile).  The rest of this junk is mainly configuring plugins for Scala &#8211; don&#8217;t worry about it.  The upshot is that you can a) run this all using <code>mvn jetty:run</code>, and b) can generate an Eclipse project using <code>mvn eclipse:eclipse</code>.</p>
<pre class="brush: xml;">
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd&quot;&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
    &lt;groupId&gt;com.pongr&lt;/groupId&gt;
    &lt;artifactId&gt;jerseyguicescala&lt;/artifactId&gt;
    &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
    &lt;packaging&gt;jar&lt;/packaging&gt;
    &lt;name&gt;jerseyguicescala&lt;/name&gt;
    &lt;properties&gt;
        &lt;jersey-version&gt;1.1.1-ea&lt;/jersey-version&gt;
    &lt;/properties&gt;
    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.sun.jersey&lt;/groupId&gt;
            &lt;artifactId&gt;jersey-server&lt;/artifactId&gt;
            &lt;version&gt;${jersey-version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.sun.jersey.contribs&lt;/groupId&gt;
            &lt;artifactId&gt;jersey-guice&lt;/artifactId&gt;
            &lt;version&gt;${jersey-version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.sun.jersey.contribs&lt;/groupId&gt;
            &lt;artifactId&gt;jersey-scala&lt;/artifactId&gt;
            &lt;version&gt;${jersey-version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;javax.servlet&lt;/groupId&gt;
            &lt;artifactId&gt;servlet-api&lt;/artifactId&gt;
            &lt;version&gt;2.5&lt;/version&gt;
            &lt;scope&gt;provided&lt;/scope&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;
    &lt;build&gt;
        &lt;plugins&gt;
            &lt;!-- Run with &quot;mvn jetty:run&quot; --&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.mortbay.jetty&lt;/groupId&gt;
                &lt;artifactId&gt;maven-jetty-plugin&lt;/artifactId&gt;
                &lt;version&gt;6.1.19&lt;/version&gt;
                &lt;configuration&gt;
                    &lt;contextPath&gt;/&lt;/contextPath&gt;
                &lt;/configuration&gt;
            &lt;/plugin&gt;
            &lt;!-- Begin scala plugins, inspired by: http://scala-tools.org/mvnsites/maven-scala-plugin/usage_java.html --&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.scala-tools&lt;/groupId&gt;
                &lt;artifactId&gt;maven-scala-plugin&lt;/artifactId&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;id&gt;scala-compile-first&lt;/id&gt;
                        &lt;phase&gt;process-resources&lt;/phase&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;add-source&lt;/goal&gt;
                            &lt;goal&gt;compile&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                    &lt;execution&gt;
                        &lt;id&gt;scala-test-compile&lt;/id&gt;
                        &lt;phase&gt;process-test-resources&lt;/phase&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;testCompile&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                &lt;/executions&gt;
            &lt;/plugin&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
                &lt;configuration&gt;
                    &lt;source&gt;1.6&lt;/source&gt;
                    &lt;target&gt;1.6&lt;/target&gt;
                &lt;/configuration&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;phase&gt;compile&lt;/phase&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;compile&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                &lt;/executions&gt;
            &lt;/plugin&gt;
            &lt;plugin&gt;
                &lt;artifactId&gt;maven-eclipse-plugin&lt;/artifactId&gt;
                &lt;configuration&gt;
                    &lt;sourceIncludes&gt;
                        &lt;sourceInclude&gt;**/*.scala&lt;/sourceInclude&gt;
                    &lt;/sourceIncludes&gt;
                    &lt;buildcommands&gt;
                        &lt;buildcommand&gt;ch.epfl.lamp.sdt.core.scalabuilder&lt;/buildcommand&gt;
                    &lt;/buildcommands&gt;
                    &lt;additionalProjectnatures&gt;
                        &lt;!-- This nature gets put after org.eclipse.jdt.core.javanature in .project so Eclipse has a J badge on the project instead of an S --&gt;
                        &lt;projectnature&gt;ch.epfl.lamp.sdt.core.scalanature&lt;/projectnature&gt;
                    &lt;/additionalProjectnatures&gt;
                    &lt;classpathContainers&gt;
                        &lt;classpathContainer&gt;org.eclipse.jdt.launching.JRE_CONTAINER&lt;/classpathContainer&gt;
                        &lt;classpathContainer&gt;ch.epfl.lamp.sdt.launching.SCALA_CONTAINER&lt;/classpathContainer&gt;
                    &lt;/classpathContainers&gt;
                &lt;/configuration&gt;
            &lt;/plugin&gt;
            &lt;!-- http://groups.google.com/group/liftweb/browse_thread/thread/3dac7002f9e59546/3918bba2f7a92cd3?pli=1 --&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;
                &lt;artifactId&gt;build-helper-maven-plugin&lt;/artifactId&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;id&gt;add-source&lt;/id&gt;
                        &lt;phase&gt;generate-sources&lt;/phase&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;add-source&lt;/goal&gt;
                        &lt;/goals&gt;
                        &lt;configuration&gt;
                            &lt;sources&gt;
                                &lt;source&gt;src/main/scala&lt;/source&gt;
                            &lt;/sources&gt;
                        &lt;/configuration&gt;
                    &lt;/execution&gt;
                    &lt;execution&gt;
                        &lt;id&gt;add-test-source&lt;/id&gt;
                        &lt;phase&gt;generate-sources&lt;/phase&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;add-test-source&lt;/goal&gt;
                        &lt;/goals&gt;
                        &lt;configuration&gt;
                            &lt;sources&gt;
                                &lt;source&gt;src/test/scala&lt;/source&gt;
                            &lt;/sources&gt;
                        &lt;/configuration&gt;
                    &lt;/execution&gt;
                &lt;/executions&gt;
            &lt;/plugin&gt;
            &lt;!-- End scala plugins --&gt;
        &lt;/plugins&gt;
    &lt;/build&gt;
&lt;/project&gt;
</pre>
<p>Next up, create the src/main/webapp/WEB-INF/web.xml file.  This just registers our special GuiceConfig class that, uh, configures Guice.</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app xmlns=&quot;http://java.sun.com/xml/ns/j2ee&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd&quot; metadata-complete=&quot;false&quot; version=&quot;2.5&quot;&gt;
    &lt;listener&gt;
        &lt;listener-class&gt;com.pongr.GuiceConfig&lt;/listener-class&gt;
    &lt;/listener&gt;
    &lt;filter&gt;
        &lt;filter-name&gt;guiceFilter&lt;/filter-name&gt;
        &lt;filter-class&gt;com.google.inject.servlet.GuiceFilter&lt;/filter-class&gt;
    &lt;/filter&gt;
    &lt;filter-mapping&gt;
        &lt;filter-name&gt;guiceFilter&lt;/filter-name&gt;
        &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
    &lt;/filter-mapping&gt;
&lt;/web-app&gt;
</pre>
<p>We&#8217;ll create an example Guice module in the src/main/java/com/pongr/ExampleModule.java file.  It just binds a message String that we&#8217;ll inject into our resource classes later.</p>
<pre class="brush: java;">
package com.pongr;

import com.google.inject.*;
import com.google.inject.name.*;

public class ExampleModule extends AbstractModule
{
    @Override
    protected void configure()
    {
        bindConstant().annotatedWith(Names.named(&quot;message&quot;)).to(&quot;Hello, World!&quot;);
    }
}
</pre>
<p>Next up is src/main/java/com/pongr/GuiceConfig.java where we connect Jersey to Guice.  This is where we create the Guice Injector using our ExampleModule and configure any Jersey properties, like the package(s) that contain our resource classes.</p>
<pre class="brush: java;">
package com.pongr;

import java.util.*;

import com.google.inject.*;
import com.google.inject.servlet.*;
import com.sun.jersey.api.core.*;
import com.sun.jersey.guice.spi.container.servlet.*;

public class GuiceConfig extends GuiceServletContextListener
{
    @Override
    protected Injector getInjector()
    {
        final Map&lt;String, String&gt; params = new HashMap&lt;String, String&gt;();
        params.put(PackagesResourceConfig.PROPERTY_PACKAGES, &quot;com.pongr&quot;);
        return Guice.createInjector(new ExampleModule(), new ServletModule()
        {
            @Override
            protected void configureServlets()
            {
                serve(&quot;/*&quot;).with(GuiceContainer.class, params);
            }
        });
    }
}
</pre>
<p>Now for the fun!  This src/main/java/com/pongr/JavaResource.java file gets the message String injected and displays it.</p>
<pre class="brush: java;">
package com.pongr;

import javax.ws.rs.*;
import javax.ws.rs.core.*;

import com.google.inject.*;
import com.google.inject.name.*;

@Path(&quot;java&quot;)
public class JavaResource
{
    private String message;

    @Inject
    public JavaResource(@Named(&quot;message&quot;) String message)
    {
        this.message = message;
    }

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String get()
    {
        return &quot;From Java: &quot; + message;
    }
}
</pre>
<p>And for good measure here&#8217;s src/main/scala/com/pongr/ScalaResource.scala.  Same as JavaResource, except in Scala.  The Guice @Inject and @Named annotations can be a bit tricky for constructor injection, so here&#8217;s how it&#8217;s done.</p>
<pre class="brush: java;">
package com.pongr

import javax.ws.rs._
import javax.ws.rs.core._

import com.google.inject._
import com.google.inject.name._

@Path(&quot;scala&quot;)
class ScalaResource @Inject() (@Named(&quot;message&quot;) message: String) {
  @GET
  @Produces(Array(MediaType.TEXT_PLAIN))
  def get(): String = &quot;From Scala: &quot; + message
}
</pre>
<p>That&#8217;s it!  Now just run <code>mvn jetty:run</code> on your command line and hit <a href="http://localhost:8080/java">http://localhost:8080/java</a> and <a href="http://localhost:8080/scala">http://localhost:8080/scala</a> in your browser to see these resources in action.  As always, you can also visit <a href="http://localhost:8080/application.wadl">http://localhost:8080/application.wadl</a> to get an overview of the available resources.  Enjoy!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/zcox.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/zcox.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/zcox.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/zcox.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/zcox.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/zcox.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/zcox.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/zcox.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/zcox.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/zcox.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/zcox.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/zcox.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/zcox.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/zcox.wordpress.com/179/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=zcox.wordpress.com&amp;blog=8766317&amp;post=179&amp;subd=zcox&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://zcox.wordpress.com/2009/09/22/jersey-guice-scala/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/acc13d0a0206b114de1590b2e0193426?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Zach</media:title>
		</media:content>
	</item>
		<item>
		<title>Dynamically Generating Zip Files in Jersey</title>
		<link>http://zcox.wordpress.com/2009/08/26/dynamically-generating-zip-files-in-jersey/</link>
		<comments>http://zcox.wordpress.com/2009/08/26/dynamically-generating-zip-files-in-jersey/#comments</comments>
		<pubDate>Wed, 26 Aug 2009 11:43:02 +0000</pubDate>
		<dc:creator>Zach Cox</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[jersey]]></category>
		<category><![CDATA[zip]]></category>

		<guid isPermaLink="false">http://zcox.wordpress.com/?p=163</guid>
		<description><![CDATA[We often need to pull a large number of rows from a database table, split those rows up into n groups, and write each group out to a separate text file.  These text files are then processed by another application.  Each text file starts with the number of rows in the file on the first [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=zcox.wordpress.com&amp;blog=8766317&amp;post=163&amp;subd=zcox&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>We often need to pull a large number of rows from a database table, split those rows up into <em>n</em> groups, and write each group out to a separate text file.  These text files are then processed by another application.  Each text file starts with the number of rows in the file on the first line, and then contains each row on its own line after that.  It became a pain to generate these files by hand, so I added a new resource to our <a href="https://jersey.dev.java.net/">Jersey</a>-based web service that would generate all of the files and wrap them all up into a single .zip file.  The processing app also used to be run by hand, but it&#8217;s now totally automated, so it obtains the .zip file, unzips it, and processes each individual file.</p>
<p>Here is the resource we ended up with, except for this blog I&#8217;m just generating a list of 100 random strings instead of pulling rows from a real database:</p>
<pre class="brush: java;">
import java.io.*;
import java.util.*;
import java.util.zip.*;

import javax.ws.rs.*;

@Path(&quot;/files&quot;)
public class FilesResource
{
    @GET
    @Produces(&quot;application/x-zip-compressed&quot;)
    public InputStream getZipFile(@QueryParam(&quot;per_file&quot;) @DefaultValue(&quot;25&quot;) final int perFile)
            throws IOException
    {
        //we write to the PipedOutputStream
        //that data is then available in the PipedInputStream which we return
        final PipedOutputStream sink = new PipedOutputStream();
        PipedInputStream source = new PipedInputStream(sink);

        //apparently we need to write to the PipedOutputStream in a separate thread
        Runnable runnable = new Runnable()
        {
            public void run()
            {
                //PrintStream =&gt; BufferedOutputStream =&gt; ZipOutputStream =&gt; PipedOutputStream
                ZipOutputStream zip = new ZipOutputStream(sink);
                PrintStream writer = new PrintStream(new BufferedOutputStream(zip));

                try
                {
                    //break the strings up into multiple files
                    List&lt;String&gt; strings = getStrings();
                    int stringCount = strings.size();
                    int fileCount = (int) Math.ceil((double) stringCount / (double) perFile);
                    for (int file = 0; file &lt; fileCount; file++)
                    {
                        zip.putNextEntry(new ZipEntry(&quot;file&quot; + (file + 1) + &quot;.txt&quot;));
                        int first = file * perFile;
                        int last = Math.min((file + 1) * perFile, stringCount);
                        int imagesInFile = last - first;
                        writer.println(imagesInFile);
                        for (int i = first; i &lt; last; i++)
                            writer.println(strings.get(i));
                        writer.flush();
                        zip.closeEntry();
                    }

                    //also include a single file with all strings
                    writer.println(stringCount);
                    zip.putNextEntry(new ZipEntry(&quot;file.txt&quot;));
                    for (int i = 0; i &lt; stringCount; i++)
                        writer.println(strings.get(i));
                    writer.flush();
                    zip.closeEntry();
                }
                catch (IOException e)
                {
                }
                writer.flush();
                writer.close();
            }
        };
        Thread writerThread = new Thread(runnable, &quot;FileGenerator&quot;);
        writerThread.start();

        return source;
    }

    private List&lt;String&gt; getStrings()
    {
        List&lt;String&gt; strings = new ArrayList&lt;String&gt;();
        for (int i = 0; i &lt; 100; i++)
            strings.add(String.valueOf(Math.random()));
        return strings;
    }
}
</pre>
<p>The getZipFile() method will be called in response to a GET /files request.  I also <a href="http://zcox.wordpress.com/2009/08/11/uri-extensions-in-jersey/">registered the .zip URI extension</a> so it will also respond to GET /files.zip.  By default it will split up the strings into groups of 25, but the per_file query parameter can be specified in the request to change that, like GET /files.zip?per_file=50 to split them into groups of 50.</p>
<p>The easiest way to create a .zip file in Java is using <a href="http://java.sun.com/javase/6/docs/api/java/util/zip/ZipOutputStream.html">ZipOutputStream</a>.  Once you have that created you call its putNextEntry() method to start a new file within the .zip file.  We also wrapped the ZipOutputStream in a <a href="http://java.sun.com/javase/6/docs/api/java/io/PrintStream.html">PrintStream</a>, and write the contents of the text files by calling println() on the PrintStream (there&#8217;s also a <a href="http://java.sun.com/javase/6/docs/api/java/io/BufferedOutputStream.html">BufferedOutputStream</a> in there for good measure).</p>
<p>Jersey is smart enough to read the data from an InputStream and use it as the HTTP response body, so ultimately we need to return an InputStream.  By hooking the ZipOutputStream up to a <a href="http://java.sun.com/javase/6/docs/api/java/io/PipedOutputStream.html">PipedOutputStream</a>, and then connecting the PipedOutputStream to a <a href="http://java.sun.com/javase/6/docs/api/java/io/PipedInputStream.html">PipedInputStream</a>, Jersey can read this all of this zip file data from the PipedInputStream.  It&#8217;s best to write-to and read-from these piped streams in different threads so we start a new writing thread and return the PipedInputStream right away.</p>
<p>This ends up working perfectly: the resource at http://site.com/files.zip feels like a static zip file, but is really generated dynamically on every request.  It also can now be accessed overy HTTP from any machine and processed automatically.  If it was really expensive to generate we could cache it and re-generate only when one of the rows in the database changed, but for our purposes it&#8217;s a cheap .zip file to generate.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/zcox.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/zcox.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/zcox.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/zcox.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/zcox.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/zcox.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/zcox.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/zcox.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/zcox.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/zcox.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/zcox.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/zcox.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/zcox.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/zcox.wordpress.com/163/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=zcox.wordpress.com&amp;blog=8766317&amp;post=163&amp;subd=zcox&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://zcox.wordpress.com/2009/08/26/dynamically-generating-zip-files-in-jersey/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/acc13d0a0206b114de1590b2e0193426?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Zach</media:title>
		</media:content>
	</item>
		<item>
		<title>iPhone + Gmail = You Need GPush</title>
		<link>http://zcox.wordpress.com/2009/08/24/iphone-gmail-you-need-gpush/</link>
		<comments>http://zcox.wordpress.com/2009/08/24/iphone-gmail-you-need-gpush/#comments</comments>
		<pubDate>Mon, 24 Aug 2009 14:10:29 +0000</pubDate>
		<dc:creator>Zach Cox</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[gmail]]></category>
		<category><![CDATA[gpush]]></category>
		<category><![CDATA[imap]]></category>
		<category><![CDATA[iphone]]></category>

		<guid isPermaLink="false">http://zcox.wordpress.com/?p=158</guid>
		<description><![CDATA[GPush is an awesome new iPhone app by Tiverias Apps that notifies you when you receive an email to your Gmail account.  Its first few days were a bit sketchy but it seems to be working great now.  I have Gmail open in Firefox all day and GPush pretty much always notifies me of a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=zcox.wordpress.com&amp;blog=8766317&amp;post=158&amp;subd=zcox&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>GPush is an awesome new iPhone app by <a href="http://tiveriasapps.com/index.php">Tiverias Apps</a> that notifies you when you receive an email to your Gmail account.  Its first few days were a bit sketchy but it seems to be working great now.  I have Gmail open in Firefox all day and GPush pretty much always notifies me of a new email before I see the little (1) on the Gmail tab.</p>
<p>Entrepreneurs and product managers everywhere should take note of this product.  First off, the problem they tackled meets the three important criteria:</p>
<ol>
<li>Pervasive: everyone with an iPhone and a Gmail account has to wait for the iPhone to poll Gmail for new emails, every 15 mins, 30 mins, or 1 hour depending on settings (while their friends with BlackBerries get emails instantly)</li>
<li>Urgent: that market has had the problem since the iPhone was originally released</li>
<li>Willing to pay: FWIW I&#8217;m part of this market and was more than happy to pay $0.99 for a solution to this problem</li>
</ol>
<p>Their solution is just about perfect.  It&#8217;s incredibly simple: you install the app, give it your Gmail username &amp; password, and that&#8217;s it.  And as long as they keep the service working properly it works great: you&#8217;re notified instantly when you get a new email to your Gmail address.</p>
<p>I know there have been a lot of unhappy GPush users so far, but it&#8217;s only been out for about a week.  I&#8217;m willing to cut them some slack at this point, and I&#8217;ve seen an incredible improvement over the last few days.  If GPush turns out to be a big fail long-term I&#8217;ll be happy to criticize it, but at this point I think Tiverias has done an awesome job!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/zcox.wordpress.com/158/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/zcox.wordpress.com/158/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/zcox.wordpress.com/158/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/zcox.wordpress.com/158/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/zcox.wordpress.com/158/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/zcox.wordpress.com/158/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/zcox.wordpress.com/158/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/zcox.wordpress.com/158/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/zcox.wordpress.com/158/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/zcox.wordpress.com/158/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/zcox.wordpress.com/158/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/zcox.wordpress.com/158/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/zcox.wordpress.com/158/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/zcox.wordpress.com/158/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=zcox.wordpress.com&amp;blog=8766317&amp;post=158&amp;subd=zcox&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://zcox.wordpress.com/2009/08/24/iphone-gmail-you-need-gpush/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/acc13d0a0206b114de1590b2e0193426?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Zach</media:title>
		</media:content>
	</item>
		<item>
		<title>Example of Implicit Conversions, Options, Extractors and Tuples</title>
		<link>http://zcox.wordpress.com/2009/08/20/example-of-implicit-conversions-options-extractors-and-tuples/</link>
		<comments>http://zcox.wordpress.com/2009/08/20/example-of-implicit-conversions-options-extractors-and-tuples/#comments</comments>
		<pubDate>Thu, 20 Aug 2009 17:44:50 +0000</pubDate>
		<dc:creator>Zach Cox</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[extractor]]></category>
		<category><![CDATA[implicit conversion]]></category>
		<category><![CDATA[option]]></category>
		<category><![CDATA[tuple]]></category>

		<guid isPermaLink="false">http://zcox.wordpress.com/?p=152</guid>
		<description><![CDATA[While writing a new web service resource today I had the chance to use some pretty awesome parts of Scala, and wanted to share some of them.  We integrate with Twitter and have a POJO like this TwitterUser class: It&#8217;s been stripped down to only the relevant property, in this case the user&#8217;s full name [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=zcox.wordpress.com&amp;blog=8766317&amp;post=152&amp;subd=zcox&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>While writing a new web service resource today I had the chance to use some pretty awesome parts of Scala, and wanted to share some of them.  We integrate with Twitter and have a POJO like this TwitterUser class:</p>
<pre class="brush: java;">
package com.pongr.twitter;

public class TwitterUser
{
    private String name;

    public TwitterUser()
    {
        this(null);
    }

    public TwitterUser(String name)
    {
        setName(name);
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }
}
</pre>
<p>It&#8217;s been stripped down to only the relevant property, in this case the user&#8217;s full name that they specified on their Twitter account.  This new resource sends back various information about a user to our mobile apps, including their Twitter info.  Since I wrote this new resource in Scala I decided to &#8220;scalafy&#8221; (scalify?) the TwitterUser class a bit.</p>
<p>First off, one of our users may not have linked to their Twitter account, so the TwitterUser object might be null.  And even if they have, the name we get back from the Twitter API will be null if they haven&#8217;t entered a name, or may just be a duplicate of their screen name (like @zcox).  We need to split up the name into valid first and last names, so this seemed like a good place to be using an Option[String] instead of just a String, which is a best practice from the <a href="http://www.apress.com/book/view/1430219890">Beginning Scala</a> book.  So the TwitterInfo class ended up looking like this:</p>
<pre class="brush: java;">
package com.pongr.twitter

class TwitterInfo(user: Option[TwitterUser]) {
  val NameRegex = &quot;&quot;&quot;(.*?)\s+(.*)&quot;&quot;&quot;.r
  val name = user.flatMap(_.getName match {
    case NameRegex(first, last) =&gt; Some((first, last))
    case _ =&gt; None
  })
  val firstName = name.map(_._1)
  val lastName = name.map(_._2)
}

object TwitterInfo {
  implicit def twitterUser2TwitterInfo(user: TwitterUser) = new TwitterInfo(if (user == null) None else Some(user))
}
</pre>
<p>Another thing to note is the use of a regular expression as an extractor to split up the Twitter name into separate first and last names.  I picked up this technique from the <a href="http://www.artima.com/shop/programming_in_scala">Programming in Scala</a> book and I have to say that it makes the code incredibly intuitive.  I also made the name field a tuple to reuse this regular expression extraction: the firstName and lastName fields are then initialized to the first and second parts of it, respectively.</p>
<p>Implicit conversions continue to amaze me so I created the twitterUser2TwitterInfo method that converts a TwitterUser object into a TwitterInfo.  Putting all of this together, we can use this TwitterInfo class to safely obtain the user&#8217;s Twitter name:</p>
<pre class="brush: java;">
package com.pongr.twitter

import TwitterInfo._

object App {
  def main(args : Array[String]) : Unit = {
    print(new TwitterUser)
    print(new TwitterUser(&quot;asdf&quot;))
    print(new TwitterUser(&quot;John Smith&quot;))
  }

  def print(user: TwitterUser) = println(user.lastName.getOrElse(&quot;N/A&quot;) + &quot;, &quot; + user.firstName.getOrElse(&quot;N/A&quot;))
}
</pre>
<p>The implicit conversion lets us (appear to) call TwitterInfo methods right on the TwitterUser object, and since the firstName and lastName fields are each an Option[String] we can gracefully handle the case where we don&#8217;t have the Twitter name.  Running the above test app prints out the following:</p>
<pre>N/A, N/A
N/A, N/A
Smith, John</pre>
<p>I know this is a pretty simple example, but I thought it was a practical demonstration of some of the techniques that make Scala such a fun language to program with.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/zcox.wordpress.com/152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/zcox.wordpress.com/152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/zcox.wordpress.com/152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/zcox.wordpress.com/152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/zcox.wordpress.com/152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/zcox.wordpress.com/152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/zcox.wordpress.com/152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/zcox.wordpress.com/152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/zcox.wordpress.com/152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/zcox.wordpress.com/152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/zcox.wordpress.com/152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/zcox.wordpress.com/152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/zcox.wordpress.com/152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/zcox.wordpress.com/152/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=zcox.wordpress.com&amp;blog=8766317&amp;post=152&amp;subd=zcox&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://zcox.wordpress.com/2009/08/20/example-of-implicit-conversions-options-extractors-and-tuples/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/acc13d0a0206b114de1590b2e0193426?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Zach</media:title>
		</media:content>
	</item>
		<item>
		<title>Simple JDBC Queries in Scala</title>
		<link>http://zcox.wordpress.com/2009/08/17/simple-jdbc-queries-in-scala/</link>
		<comments>http://zcox.wordpress.com/2009/08/17/simple-jdbc-queries-in-scala/#comments</comments>
		<pubDate>Mon, 17 Aug 2009 19:21:47 +0000</pubDate>
		<dc:creator>Zach Cox</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[jdbc]]></category>
		<category><![CDATA[partially applied functions]]></category>

		<guid isPermaLink="false">http://zcox.wordpress.com/?p=140</guid>
		<description><![CDATA[The Beginning Scala book has a great example of using partially applied functions to automatically close JDBC connections. Today I needed to use some complex SQL outside of our ORM and extended this code sample to make it incredibly simple &#38; safe. The using and bmap methods are from the book; the query and queryEach [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=zcox.wordpress.com&amp;blog=8766317&amp;post=140&amp;subd=zcox&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://www.apress.com/book/view/1430219890">Beginning Scala</a> book has a great example of using partially applied functions to automatically close JDBC connections.  Today I needed to use some complex SQL outside of our ORM and extended this code sample to make it incredibly simple &amp; safe.</p>
<p>The using and bmap methods are from the book; the query and queryEach methods are my creations:</p>
<pre class="brush: java;">
object Control {
  def using[Closeable &lt;: {def close(): Unit}, B](closeable: Closeable)(getB: Closeable =&gt; B): B =
    try {
      getB(closeable)
    } finally {
      closeable.close()
    }

  import scala.collection.mutable.ListBuffer

  def bmap[T](test: =&gt; Boolean)(block: =&gt; T): List[T] = {
    val ret = new ListBuffer[T]
    while(test) ret += block
    ret.toList
  }

  import java.sql._

  /** Executes the SQL and processes the result set using the specified function. */
  def query[B](connection: Connection, sql: String)(process: ResultSet =&gt; B): B =
    using (connection) { connection =&gt;
      using (connection.createStatement) { statement =&gt;
        using (statement.executeQuery(sql)) { results =&gt;
          process(results)
        }
      }
    }

  /** Executes the SQL and uses the process function to convert each row into a T. */
  def queryEach[T](connection: Connection, sql: String)(process: ResultSet =&gt; T): List[T] =
    query(connection, sql) { results =&gt;
      bmap(results.next) {
        process(results)
      }
    }
}
</pre>
<p>The using method just ensures that something with a close() method gets closed after it&#8217;s used, while bmap collects the results of some function into a list.  I found the using method resulted in a fair amount of boilerplate code, so I factored that out into the query method.  You just give it a Connection object and an SQL string and it will handle creating the Statement and ResultSet, passing the ResultSet to your custom processing function, and then closing everything safely for you.</p>
<p>The queryEach method also eliminates some common boilerplate.  It builds on the query method by using each row in the ResultSet to create some domain object and collecting all of those objects into a list.  As the example usage below shows, you just give queryEach your connection and SQL, as well as some simple code to process a single row in the ResultSet:</p>
<pre class="brush: java;">
import com.whatever.Control._
import java.sql._

val conn: Connection = ...
val people = queryEach(conn, &quot;SELECT * FROM person&quot;) {rs =&gt;
  new Person(rs.getString(&quot;name&quot;), rs.getInt(&quot;age&quot;), rs.getBoolean(&quot;valid&quot;))
}
</pre>
<p>I think this results in some very compact and intuitive code.  And reusing all of the boilerplate in the Control methods ensures that you don&#8217;t forget to close a Statement or ResultSet.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/zcox.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/zcox.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/zcox.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/zcox.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/zcox.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/zcox.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/zcox.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/zcox.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/zcox.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/zcox.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/zcox.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/zcox.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/zcox.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/zcox.wordpress.com/140/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=zcox.wordpress.com&amp;blog=8766317&amp;post=140&amp;subd=zcox&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://zcox.wordpress.com/2009/08/17/simple-jdbc-queries-in-scala/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/acc13d0a0206b114de1590b2e0193426?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Zach</media:title>
		</media:content>
	</item>
		<item>
		<title>URI Extensions in Jersey</title>
		<link>http://zcox.wordpress.com/2009/08/11/uri-extensions-in-jersey/</link>
		<comments>http://zcox.wordpress.com/2009/08/11/uri-extensions-in-jersey/#comments</comments>
		<pubDate>Tue, 11 Aug 2009 20:40:54 +0000</pubDate>
		<dc:creator>Zach Cox</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[format]]></category>
		<category><![CDATA[jersey]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[uri]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://zcox.wordpress.com/?p=135</guid>
		<description><![CDATA[Jersey provides an excellent system for easily supporting multiple representations of resources. You use the @Produces annotation to define which formats a resource method supports: In this case clients can obtain the representation of the thing resource in either XML or JSON format (assuming you&#8217;ve registered corresponding MessageBodyWriters for the Thing class).  Just by including [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=zcox.wordpress.com&amp;blog=8766317&amp;post=135&amp;subd=zcox&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="https://jersey.dev.java.net/">Jersey</a> provides an excellent system for easily supporting multiple representations of resources.  You use the <a href="https://jsr311.dev.java.net/nonav/releases/1.1/javax/ws/rs/Produces.html">@Produces</a> annotation to define which formats a resource method supports:</p>
<pre class="brush: java;">
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Thing getThing()
{
    Thing thing = ...;
    return thing;
}
</pre>
<p>In this case clients can obtain the representation of the thing resource in either XML or JSON format (assuming you&#8217;ve registered corresponding <a href="https://jsr311.dev.java.net/nonav/releases/1.1/javax/ws/rs/ext/MessageBodyWriter.html">MessageBodyWriters</a> for the Thing class).  Just by including the @Produces annotation, Jersey handles sending the response back in the proper format and will even send a 415 Unsupported Media Type response automatically if the client requests the resource in an unsupported format.</p>
<p>By default Jersey uses the <a href="http://www.w3.org/Protocols/HTTP/HTRQ_Headers.html#z3">Accept</a> request header to determine which response format to use.  Setting request headers in client apps can be cumbersome though, so a more convenient approach is to use URI extensions.  So if you want the http://site.com/thing resource as XML you GET http://site.com/thing.xml, or GET http://site.com/thing.json if you want its JSON representation.</p>
<p>To tell Jersey to use URI extensions, you create a cusom <a href="https://jersey.dev.java.net/nonav/apidocs/1.1.0-ea/jersey/com/sun/jersey/api/core/PackagesResourceConfig.html">PackagesResourceConfig</a> implementation and set up the mappings between extensions and media types:</p>
<pre class="brush: java;">
import java.util.*;
import javax.ws.rs.core.*;
import com.sun.jersey.api.core.*;

/** Registers URI extensions for some common media types.  This lets clients specify the desired
 * response format right in the URI like http://site.com/whatever.xml instead of
 * http://site.com/whatever with an Accept:application/xml header. */
public class UriExtensionsConfig extends PackagesResourceConfig
{
    private Map&lt;String, MediaType&gt; mediaTypeMap;

    public UriExtensionsConfig()
    {
        super();
    }

    public UriExtensionsConfig(Map&lt;String, Object&gt; props)
    {
        super(props);
    }

    public UriExtensionsConfig(String[] paths)
    {
        super(paths);
    }

    @Override
    public Map&lt;String, MediaType&gt; getMediaTypeMappings()
    {
        if (mediaTypeMap == null)
        {
            mediaTypeMap = new HashMap&lt;String, MediaType&gt;();
            mediaTypeMap.put(&quot;json&quot;, MediaType.APPLICATION_JSON_TYPE);
            mediaTypeMap.put(&quot;xml&quot;, MediaType.APPLICATION_XML_TYPE);
            mediaTypeMap.put(&quot;txt&quot;, MediaType.TEXT_PLAIN_TYPE);
            mediaTypeMap.put(&quot;html&quot;, MediaType.TEXT_HTML_TYPE);
            mediaTypeMap.put(&quot;xhtml&quot;, MediaType.APPLICATION_XHTML_XML_TYPE);
            MediaType jpeg = new MediaType(&quot;image&quot;, &quot;jpeg&quot;);
            mediaTypeMap.put(&quot;jpg&quot;, jpeg);
            mediaTypeMap.put(&quot;jpeg&quot;, jpeg);
            mediaTypeMap.put(&quot;zip&quot;, new MediaType(&quot;application&quot;, &quot;x-zip-compressed&quot;));
        }
        return mediaTypeMap;
    }
}
</pre>
<p>You register the UriExtensionsConfig in web.xml like this:</p>
<pre class="brush: xml;">
    &lt;servlet&gt;
        ...
        &lt;init-param&gt;
            &lt;param-name&gt;com.sun.jersey.config.property.resourceConfigClass&lt;/param-name&gt;
            &lt;param-value&gt;com.pongr.rest.config.UriExtensionsConfig&lt;/param-value&gt;
        &lt;/init-param&gt;
    &lt;/servlet&gt;
</pre>
<p>This provides yet another way to make your web services more user-friendly.  Clients can still use the Accept header but can also use standard URI extensions to specify the desired response format.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/zcox.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/zcox.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/zcox.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/zcox.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/zcox.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/zcox.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/zcox.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/zcox.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/zcox.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/zcox.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/zcox.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/zcox.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/zcox.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/zcox.wordpress.com/135/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=zcox.wordpress.com&amp;blog=8766317&amp;post=135&amp;subd=zcox&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://zcox.wordpress.com/2009/08/11/uri-extensions-in-jersey/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/acc13d0a0206b114de1590b2e0193426?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Zach</media:title>
		</media:content>
	</item>
		<item>
		<title>Same Snippet, Different Designs</title>
		<link>http://zcox.wordpress.com/2009/08/10/same-snippet-different-designs/</link>
		<comments>http://zcox.wordpress.com/2009/08/10/same-snippet-different-designs/#comments</comments>
		<pubDate>Mon, 10 Aug 2009 17:31:37 +0000</pubDate>
		<dc:creator>Zach Cox</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[lift]]></category>
		<category><![CDATA[snippets]]></category>
		<category><![CDATA[templates]]></category>

		<guid isPermaLink="false">http://zcox.wordpress.com/?p=118</guid>
		<description><![CDATA[You&#8217;re building a web site and the designers send you XHTML templates with essentially the same form on two different pages, but each page uses a slightly different layout. Being the good coder you are, you want to reuse the same submit-handling code on the back-end to prevent code duplication. This is easy to handle [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=zcox.wordpress.com&amp;blog=8766317&amp;post=118&amp;subd=zcox&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>You&#8217;re building a web site and the designers send you XHTML templates with essentially the same form on two different pages, but each page uses a slightly different layout.  Being the good coder you are, you want to reuse the same submit-handling code on the back-end to prevent code duplication.  This is easy to handle using Lift snippets.</p>
<p>The form lets a user add a new restaurant to our restaurant review site.  So we create a snippet like this (it just prints the submitted data for now):</p>
<pre class="brush: java;">
import scala.xml._
import net.liftweb.util.Helpers._
import net.liftweb.http._

class CreateRestaurant {
  def render(xhtml: NodeSeq): NodeSeq = {
    var name = &quot;&quot;
    var address = &quot;&quot;
    var phone = &quot;&quot;

    def createRestaurant() = println(&quot;Created &quot; + name + &quot;, &quot; + address + &quot;, &quot; + phone)

    bind(&quot;form&quot;, xhtml, &quot;name&quot; -&gt; SHtml.text(name, name = _),
                        &quot;address&quot; -&gt; SHtml.text(address, address = _),
                        &quot;phone&quot; -&gt; SHtml.text(phone, phone = _),
                        &quot;submit&quot; -&gt; SHtml.submit(&quot;Add&quot;, createRestaurant))
  }
}
</pre>
<p>Next we can create two different forms in our XHTML templates and bind them to the same CreateRestaurant snippet.  We are free to modify the design inside the snippet, as long as we bind the same form elements in each one.</p>
<p>Here&#8217;s the first form template:</p>
<pre class="brush: xml;">
  &lt;lift:CreateRestaurant form=&quot;POST&quot;&gt;
    &lt;h3&gt;Add a new restaurant&lt;/h3&gt;
    &lt;table&gt;
      &lt;tr&gt;&lt;td&gt;Name&lt;/td&gt;&lt;td&gt;&lt;form:name&gt;&lt;input type=&quot;text&quot;/&gt;&lt;/form:name&gt;&lt;/td&gt;&lt;/tr&gt;
      &lt;tr&gt;&lt;td&gt;Address&lt;/td&gt;&lt;td&gt;&lt;form:address&gt;&lt;input type=&quot;text&quot;/&gt;&lt;/form:address&gt;&lt;/td&gt;&lt;/tr&gt;
      &lt;tr&gt;&lt;td&gt;Phone&lt;/td&gt;&lt;td&gt;&lt;form:phone&gt;&lt;input type=&quot;text&quot;/&gt;&lt;/form:phone&gt;&lt;/td&gt;&lt;/tr&gt;
      &lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;td&gt;&lt;form:submit&gt;&lt;input type=&quot;submit&quot;/&gt;&lt;/form:submit&gt;&lt;/td&gt;&lt;/tr&gt;
    &lt;/table&gt;
  &lt;/lift:CreateRestaurant&gt;
</pre>
<p>And here&#8217;s the second form template:</p>
<pre class="brush: xml;">
  &lt;lift:CreateRestaurant form=&quot;POST&quot;&gt;
    &lt;table&gt;
      &lt;tr&gt;
        &lt;th&gt;Name&lt;/th&gt;
        &lt;th&gt;Address&lt;/th&gt;
        &lt;th&gt;Phone&lt;/th&gt;
        &lt;th&gt;&lt;/th&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td&gt;&lt;form:name&gt;&lt;input type=&quot;text&quot;/&gt;&lt;/form:name&gt;&lt;/td&gt;
        &lt;td&gt;&lt;form:address&gt;&lt;input type=&quot;text&quot;/&gt;&lt;/form:address&gt;&lt;/td&gt;
        &lt;td&gt;&lt;form:phone&gt;&lt;input type=&quot;text&quot;/&gt;&lt;/form:phone&gt;&lt;/td&gt;
        &lt;td&gt;&lt;form:submit&gt;&lt;input type=&quot;submit&quot;/&gt;&lt;/form:submit&gt;&lt;/td&gt;
      &lt;/tr&gt;
    &lt;/table&gt;
  &lt;/lift:CreateRestaurant&gt;
</pre>
<p>Same form, just different layouts: the first has the fields arranged horizontally while the second lays them out vertically.  When Lift renders them they both look different but behave exactly the same way on the back-end, because they both reuse the same snippet code.</p>
<p><img class="alignnone size-full wp-image-121" title="CreateRestaurant1" src="http://zcox.files.wordpress.com/2009/08/createrestaurant1.png?w=364&#038;h=180" alt="CreateRestaurant1" width="364" height="180" /></p>
<p><img class="alignnone size-full wp-image-122" title="CreateRestaurant2" src="http://zcox.files.wordpress.com/2009/08/createrestaurant2.png?w=685&#038;h=71" alt="CreateRestaurant2" width="685" height="71" /></p>
<p>No more need to duplicate back-end form submit handling code!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/zcox.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/zcox.wordpress.com/118/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/zcox.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/zcox.wordpress.com/118/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/zcox.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/zcox.wordpress.com/118/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/zcox.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/zcox.wordpress.com/118/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/zcox.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/zcox.wordpress.com/118/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/zcox.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/zcox.wordpress.com/118/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/zcox.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/zcox.wordpress.com/118/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=zcox.wordpress.com&amp;blog=8766317&amp;post=118&amp;subd=zcox&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://zcox.wordpress.com/2009/08/10/same-snippet-different-designs/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/acc13d0a0206b114de1590b2e0193426?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Zach</media:title>
		</media:content>

		<media:content url="http://zcox.files.wordpress.com/2009/08/createrestaurant1.png" medium="image">
			<media:title type="html">CreateRestaurant1</media:title>
		</media:content>

		<media:content url="http://zcox.files.wordpress.com/2009/08/createrestaurant2.png" medium="image">
			<media:title type="html">CreateRestaurant2</media:title>
		</media:content>
	</item>
	</channel>
</rss>
