<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<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/"
	>

<channel>
	<title>scala &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/scala/</link>
	<description>Feed of posts on WordPress.com tagged "scala"</description>
	<pubDate>Thu, 26 Nov 2009 13:15:05 +0000</pubDate>

	<generator>http://en.wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[Structural Typing]]></title>
<link>http://coffeesgone.wordpress.com/2009/11/25/structural-typing/</link>
<pubDate>Thu, 26 Nov 2009 04:36:09 +0000</pubDate>
<dc:creator>Sam Baskinger</dc:creator>
<guid>http://coffeesgone.wordpress.com/2009/11/25/structural-typing/</guid>
<description><![CDATA[My excellent colleague, Luke Forehand, pointed out to me recently that Scala has structural typing. ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>My excellent colleague, <a href="http://lukeforehand.blogspot.com/">Luke Forehand</a>, pointed out to me recently that Scala has <a href="http://en.wikipedia.org/wiki/Structural_type_system"><em>structural typing</em></a>. Specifically, a <a href="http://debasishg.blogspot.com/2008/06/scala-to-java-smaller-inheritance.html">blog</a> walking through how to build a list that takes objects which have a certain method details the concept and gives a compelling example of when/where to use it.</p>
<p>This is similar to <a href="http://en.wikipedia.org/wiki/Duck_typing">duck typing</a> in that run time examination of an object is performed to see if it complies with the setup contract. However, where as duck typing simply tries to dispatch a message to an object which may fail, structural typing is a bit tighter contract which builds in checks that a certain call exists before it is called. To steal a form of the <a href="http://www.scala-lang.org/">Scala</a> example used in the linked blog article above, consider the statement:</p>
<pre style="padding-left:30px;">val myListOfThings = List[ { def f(x:Int):Int } ]</pre>
<p>The above says, <em>declare a list that only takes objects that have a function named f that takes an Int and returns an Int.</em> The beauty here is that you do not have to maintain a tree of related interfaces to bind together objects of similar or identical functionality. You can also build APIs that do not require your users to implement an interface of abstract method that, prehaps, is surrounded with loads of other method signatures and method definitions that the user really doesn&#8217;t care about.</p>
<p>I&#8217;m not looking for every excuse I can find to use this.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Jeder hat etwas, das ihn antreibt!]]></title>
<link>http://m0lch.wordpress.com/2009/11/24/jeder-hat-etwas-das-ihn-antreibt/</link>
<pubDate>Tue, 24 Nov 2009 19:55:29 +0000</pubDate>
<dc:creator>m0lch</dc:creator>
<guid>http://m0lch.wordpress.com/2009/11/24/jeder-hat-etwas-das-ihn-antreibt/</guid>
<description><![CDATA[Bestimmt kennt jeder einen der Werbespots der Volksbanken-Raiffeisenbanken, in denen das wunderschön]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p style="text-align:justify;">Bestimmt kennt jeder einen der Werbespots der Volksbanken-Raiffeisenbanken, in denen das wunderschöne Lied &#8220;Hungriges Herz&#8221; von Mia (hier als Cover von Scala) im Hintergrund zu hören ist.</p>
<p style="text-align:justify;">Ich muss zugeben, vor allem deswegen, also wegen des Liedes, gefallen mir die Werbespots. Aber viel mehr noch spricht mich der Inhalt an. Das Motto &#8220;Jeder Mensch hat etwas, das ihn antreibt&#8221; kann sicherlich jeder bejahen, was immer es auch ist, was uns antreibt. Aber allein ein Ziel, auf das es sich lohnt, hinzuarbeiten, macht das Leben doch lebenswert. Wenn man weiß, warum man etwas tut, auch wenn es Zeiten gibt, in denen das Ziel unerreichbar oder sinnlos scheint.</p>
<p style="text-align:justify;">Jetzt sollte ich mal zum Punkt kommen. Auf der Internetseite <a href="http://www.was-uns-antreibt.de" target="_blank"><span style="color:#ffcc00;"><span style="text-decoration:underline;">www.was-uns-antreibt.de</span></span></a> gibt es jetzt auch einen Dokumentarfilm, in dem die Personen, die in den Videos kurz zu sehen sind, nochmal zu Wort kommen. Für mich ist das ein toller Film, den es &#8211; nebenbei gesagt &#8211; auch kostenlos zum Download gibt.</p>
<p style="text-align:justify;">Wer Lust bekommen hat, klickt sich einfach rein, wer noch zweifelt, für den habe ich noch einen Spot:</p>
<p style="text-align:justify;"><span style='text-align:center; display: block;'><object width='425' height='350'><param name='movie' value='http://www.youtube.com/v/ro_iUmYbFXs&#038;rel=1&#038;fs=1&#038;showsearch=0&#038;hd=0' /><param name='allowfullscreen' value='true' /><param name='wmode' value='transparent' /><embed src='http://www.youtube.com/v/ro_iUmYbFXs&#038;rel=1&#038;fs=1&#038;showsearch=0&#038;hd=0' type='application/x-shockwave-flash' allowfullscreen='true' width='425' height='350' wmode='transparent'></embed></object></span></p>
<p style="text-align:justify;"><em>m0lch </em></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Dynamic Offline Reports]]></title>
<link>http://developeraspirations.wordpress.com/2009/11/23/dynamic-offline-reports/</link>
<pubDate>Tue, 24 Nov 2009 00:38:41 +0000</pubDate>
<dc:creator>jearil</dc:creator>
<guid>http://developeraspirations.wordpress.com/2009/11/23/dynamic-offline-reports/</guid>
<description><![CDATA[Many applications have the primary concern of storing and retrieving data. The raw data by itself is]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Many applications have the primary concern of storing and retrieving data. The raw data by itself is often not very useful, so an additional process is put into place to turn that data into useful information. Many applications generate these reports from the data quickly at the user&#8217;s request through either a narrow SQL select statement, in application data processing, or both. However, in larger applications where the data is too large to handle in memory at a time, processing is too heavy, and report customization is too varied, information generation needs to be pushed to its own scalable system.</p>
<p>A lot of data has various pieces of metadata associated with it naturally. Data such as what user added the record, the date it was added or modified (or both), maybe the size of the record, categories, tags, keywords, or other pieces of associate data that is used to break it up into more manageable chunks. This meta data is useful, but only if we can use it as an aggregate to generate specific information relating to the grouping of items based on this data.</p>
<p>Sometimes generating these more specific reports is as easy as adding additional WHERE or GROUP BY clauses in SQL. However, when more advanced business rules are taking place where there isn&#8217;t an easy or succinct way of extracting this information via a query, or if the query returns such a large amount of data as to cause memory issues, a different approach can be taken.</p>
<p>For instance; in an application I am currently working on we need to generate reports based on a table with about 5 million rows. The SQL queries we use can limit the amount of rows returned to perhaps a few hundred thousand for some of our larger reports. However, a lot of the data needs to be processed in application code rather than by the database itself due to some special business rules. Because of this, we end up creating a large number of objects in Java to hold these result rows. If multiple users are generating different reports we might end up holding too many of these objects in memory at a time and receive an OOM error. Also, the processing on this data can be intense enough that if the server is slammed with report requests that the entire system slows down, causing difficulties for people wanting to insert or modify data. This is the case I am in while I contemplate offline report generation.</p>
<p>The basic idea is that the main application should be concerned purely with manipulating the data of the system. That is basic CRUD stuff such as creating new records, updating them, the rare deletions, and showing single records to the user (so they can edit or delete it). We want that part of the application to remain fast, and not be effected by the purely read-only needs imposed by report generation. In order to nullify the impact, we move reporting to its own system that reads from a separate read-only replication of our production database.</p>
<p>When a report request comes in to our application, we send a request to the separate reporting system. This can be done either as a web service or maybe an RPC call. The reporting system uses its read-only copy of the data to generate the report numbers and send it back, causing no speed delay for insertion or regular operation of the main application.</p>
<p>This doesn&#8217;t solve our OOM issues however, as many drivers for our database (MySQL) return ResultSet objects with the entire contents of the results which might be too large to fit into memory. However, since we&#8217;re using a read-only list anyway we can convert the table or tables we use to process our results into flat files that can be read in on a line by line basis, perform some intermediate result processing, deallocate those lines and work on additional lines. Since our reports are mostly generating statistical data over a large data set, we can process results on that data set in parallel using multiple threads or possibly multiple computers using a Hadoop cluster.</p>
<p>By making report generation asynchronous to our applications general work flow we will free up the processing power and the connection pool that&#8217;s used to handle requests by asking users to either poll for when the result is finished or to notify the system when a report is finished and thereby avoid the instances where we use all of our available connections or resources processing reports. There is also the added possibility of continuously generating all possible report data on a separate machine or cluster to decrease access time by increasing storage requirements.</p>
<p>I&#8217;m currently researching the use of MapReduce in Hadoop for processing this flat file of all data for reports. In addition, I&#8217;m researching a few languages that are reported to be good at concurrent processing so that I can benefit from multiple cores when generating reports from our raw data. My current focus is on Scala, Erlang, and Clojure, but I do not have much to report on those areas yet. If anyone has any information those languages as far as report generation based on a largish data set (currently 5 million, but the rate of growth is fairly alarming), let me know.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Adding OpenId support to a Scala / Lift application]]></title>
<link>http://wstrange.wordpress.com/2009/11/23/adding-openid-support-to-a-scala-lift-application/</link>
<pubDate>Mon, 23 Nov 2009 23:11:18 +0000</pubDate>
<dc:creator>wstrange</dc:creator>
<guid>http://wstrange.wordpress.com/2009/11/23/adding-openid-support-to-a-scala-lift-application/</guid>
<description><![CDATA[The Lift web framework includes basic support for OpenId using the the openid4java library. I wanted]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>The <a href="http://liftweb.net">Lift </a>web framework includes basic support for <a href="http://openid.net/">OpenId</a> using the the <a href="http://code.google.com/p/openid4java/">openid4java</a> library. I wanted to learn a little more about Scala, Lift and OpenId &#8211; so what follows are my notes on how to get this running, along with some minor improvements that I have made.</p>
<p>You will want to start by familiarizing yourself with the OpenId chapter in the (rather excellent)<a href="http://groups.google.com/group/the-lift-book"> Lift book</a>.</p>
<p>Out of the box, the lift-openid support gets  you a vanilla login form where the user can enter their OpenId URL and submit the request.  Something that looks like this:</p>
<p><a href="http://wstrange.wordpress.com/files/2009/11/openidlogin.png"><img class="alignnone size-medium wp-image-169" title="openidlogin" src="http://wstrange.wordpress.com/files/2009/11/screen-shot-2009-11-23-at-3-06-09-pm.png?w=300" alt="" width="300" height="60" /></a></p>
<p>While this is nice for identity geeks, your grandma isn&#8217;t going to be using this anytime soon. The OpenId UI issues are being hotly debated as you read this, and I won&#8217;t open that can of worms. Suffice to say that mere mortals will prefer to use a &#8220;Nascar&#8221; branded interface that let&#8217;s them login using their favourite email provider such as Google or Yahoo (The Nascar UI is a reference to the logos that are plastered over the race cars).  Most users won&#8217;t have a clue what their OpenId provider (OP) URL is , but they can spot the logo of their email provider a mile away.</p>
<p>Too add a slicker login interface, I grabbed a copy Jarret Vance&#8217;s <a href="http://jvance.com/pages/JQueryOpenIDPlugin.xhtml">OpenId JQuery Plugin</a>.   Lift uses JQuery by default, so integration of Jarret&#8217;s plugin is quite easy.  The plugin consists of provider logos (put these in your /webapp/images directory), a Javascript JQuery extension (jquery-openid.js &#8211; put this in your webapp/scripts directory), and some html templates for the login page.</p>
<p>I created a Lift template for the login page and placed it under my webapp/templates-hidden directory. The template is pretty much a copy of the default template, but adds some javascript for the openid integration. In the head tag of the template include the following:</p>
<pre class="brush: xml;">

&#60;script id=&#34;jquery&#34; src=&#34;/classpath/jquery.js&#34; type=&#34;text/javascript&#34;/&#62;
 &#60;script id=&#34;json&#34; src=&#34;/classpath/json.js&#34; type=&#34;text/javascript&#34; /&#62;
 &#60;script id=&#34;openid&#34; src=&#34;/scripts/openid-jquery.js&#34;  type=&#34;text/javascript&#34;/&#62;
 &#60;script type=&#34;text/javascript&#34;&#62;

 $(document).ready(function() {
 openid.init('openIdUrl');
 });
 &#60;/script&#62;
</pre>
<p>N<em>ote that Lift performs &#8220;head&#8221; merging &#8211; which is to say that any content withing &#60;head&#62; tags in a snippet is merged in with the templates head tag. So the above approach is not strictly necessary.</em></p>
<p>Now that we have a login template, we can define the login page. Most of the content is copied verbatim from Jaret&#8217;s plugin</p>
<pre class="brush: xml;">
&#60;lift:surround with=&#34;openid&#34; at=&#34;content&#34;&#62;
 &#60;head&#62;
 &#60;title&#62;
 &#60;lift:loc&#62;Login&#60;/lift:loc&#62;
 &#60;/title&#62;
 &#60;/head&#62;
 &#60;h2&#62;
 &#60;lift:loc locid=&#34;Welcome&#34;&#62;Login Page&#60;/lift:loc&#62;
 &#60;/h2&#62;
&#60;p&#62;This site uses &#60;a href=&#34;openid.net&#34;&#62;OpenId&#60;/a&#62; so you don't have to remember yet-another password.
 &#60;br/&#62;Enter your OpenId URL, or click one one of the icons below to sign on with an existing account.
 &#60;/p&#62;
 &#60;!-- Simple OpenID Selector --&#62;
 &#60;form action=&#34;/openid/login&#34; method=&#34;post&#34; id=&#34;openid_form&#34;&#62;
 &#60;div&#62;
 &#60;ul&#62;
 &#60;li title=&#34;OpenID&#34;&#62;&#60;img src=&#34;/images/openidW.png&#34; alt=&#34;icon&#34;/&#62;
 &#60;span&#62;&#60;strong&#62;http://{your-openid-url}&#60;/strong&#62;&#60;/span&#62;&#60;/li&#62;
 &#60;li title=&#34;Google&#34;&#62;
 &#60;img src=&#34;/images/googleW.png&#34; alt=&#34;icon&#34;/&#62;&#60;span&#62;https://www.google.com/accounts/o8/id&#60;/span&#62;&#60;/li&#62;
 &#60;li title=&#34;Yahoo&#34;&#62;
 &#60;img src=&#34;/images/yahooW.png&#34; alt=&#34;icon&#34;/&#62;&#60;span&#62;http://yahoo.com/&#60;/span&#62;&#60;/li&#62;
 &#60;li title=&#34;AOL screen name&#34;&#62;
 &#60;img src=&#34;/images/aolW.png&#34; alt=&#34;icon&#34;/&#62;&#60;span&#62;http://openid.aol.com/&#60;strong&#62;username&#60;/strong&#62;&#60;/span&#62;
 &#60;/li&#62;
 &#60;/ul&#62;
 &#60;/div&#62;
 &#60;fieldset&#62;
 &#60;label for=&#34;openid_username&#34;&#62;Enter your &#60;span&#62;Provider user name&#60;/span&#62;&#60;/label&#62;
 &#60;div&#62;&#60;span&#62;&#60;/span&#62;&#60;input type=&#34;text&#34; name=&#34;openid_username&#34;/&#62;&#60;span&#62;&#60;/span&#62;
 &#60;input type=&#34;submit&#34; value=&#34;Login&#34;/&#62;&#60;/div&#62;
 &#60;/fieldset&#62;
 &#60;fieldset&#62;
 &#60;label for=&#34;openid_identifier&#34;&#62;Enter your &#60;a href=&#34;http://openid.net&#34;&#62;OpenID&#60;/a&#62;&#60;/label&#62;
 &#60;div&#62;&#60;input type=&#34;text&#34; name=&#34;openid_identifier&#34; id=&#34;openid_identifier&#34;/&#62;
 &#60;input type=&#34;submit&#34; value=&#34;Login&#34;/&#62;&#60;/div&#62;
 &#60;/fieldset&#62;
 &#60;/form&#62;
&#60;/lift:surround&#62;
</pre>
<p>For brevity I have removed some of the provider logos from the example. The nice thing about this plugin is that it is very easy to add or remove providers.</p>
<p>This gives us a nice &#8220;Nascar&#8221; login page that looks like this:</p>
<p><a href="http://wstrange.wordpress.com/files/2009/11/openid-nascar2.png"><img class="alignnone size-full wp-image-184" title="openid-nascar2" src="http://wstrange.wordpress.com/files/2009/11/openid-nascar2.png" alt="" width="600" height="249" /></a></p>
<p>Now this will make both the geeks and grandma happy.</p>
<p>In the next blog entry (when I get around to it&#8230;) I will describe how to add support for the OpenId attribute exchange protocol (AX). This enables our application to retrieve additional user attributes from the provider such as the user&#8217;s email address, screen name, preferred language, etc..  Stay tuned.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[First Look at Vaadin]]></title>
<link>http://devblog.point2.com/2009/11/22/first-look-at-vaadin/</link>
<pubDate>Sun, 22 Nov 2009 16:50:49 +0000</pubDate>
<dc:creator>Mike Nash</dc:creator>
<guid>http://devblog.point2.com/2009/11/22/first-look-at-vaadin/</guid>
<description><![CDATA[I&#8217;ve had the chance over a recent weekend to have a first crack at a web framework called Vaad]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I&#8217;ve had the chance over a recent weekend to have a first crack at a web framework called <a href="http://vaadin.com">Vaadin</a>.</p>
<p>I was originally browsing for news about the latest release of Google&#8217;s <a href="http://code.google.com/webtoolkit/">GWT</a> framework when I stumbled on a reference to Vaadin, and decided to go take a look. What I found intrigued me, and I decided to take it for a test drive, as I was down sick for a couple of days with a laptop nearby&#8230;. My back became annoyed with me, but it was worth it, I think.</p>
<p><b>First Look</b><br />
First off, the practicalities: Vaadin is open source, and with a reasonable <a href="http://vaadin.com/license">license</a>, the Apache License. The essential bits of Vaadin are contained in a single JAR, and it&#8217;s both Ant and Maven friendly right out of the box. </p>
<p>The next thing that struck me about Vaadin was the documentation. The first unusual thing about it&#8217;s documentation was the fact of it&#8217;s existence, as open source projects are downright notorious for poor documentation. Vaadin is a pleasant exception, with tons of examples, a well-organized <a href="http://vaadin.com/api/">API doc</a>, in the usual JavaDoc format, and even the &#8220;Book of Vaadin&#8221;, <a href="http://vaadin.com/book">an entire PDF book</a> (also available in hardcopy) that takes you through Vaadin in enough detail to be immediately productive.</p>
<p>Given that surprisingly pleasant start, I dug deeper, creating a little app of my own. </p>
<p><b>Just the Java, Ma&#8217;am</b><br />
The main thing that kept me interested in Vaadin once I started digging further was that it&#8217;s pure Java. Many frameworks talk about writing your UI work in Java, such as Wicket, but there&#8217;s still a corresponding template and some wiring that happens to put the code and the template together. Not so with Vaadin.</p>
<p>When they say &#8220;just Java&#8221;, they mean it &#8211; your entire UI layer is coded in Java, plain and simple. No templates, no tag libraries, no Javascript, no &#8216;nuthin. It&#8217;s reminiscent of the <a href="http://echo.nextapp.com/site/">Echo framework</a>, except in Vaadin&#8217;s case the Javascript library that your code automatically produces is Google&#8217;s GWT, instead of Echo&#8217;s own Core.JS library.</p>
<p>Unlike GWT, though, the Vaadin approach doesn&#8217;t bind you to any specific source code though, it&#8217;s just a binary jar you put on your classpath. </p>
<p>The <b>only</b> thing in my sample app, other than 2 Java files, was a web.xml and a css stylesheet, both of which were only a few lines long. And this was no &#8220;Hello, World&#8221;, either, but a rich AJAX webapp with a tree menu, fancy non-modal &#8220;fading&#8221; notifications, images, complex layouts, and a form with build-in validation. And it took maybe 4 hours of total work to produce &#8211; and that was from a standing start, as I&#8217;d never heard of Vaadin before last Thursday. Not bad, not bad at all.</p>
<p>I found I was able to get a very capable little webapp up and running with no need to invent my own components, even though I had trees and sliders and menus and other assorted goodies on the page. It worked in every browser I was able to try it in, which is certainly not the case for my own hand-rolled JavaScript most of the time <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>I haven&#8217;t yet tried creating my own custom components, but it certainly looks straightforward enough.</p>
<p>I did try linking to external resources, and included non-Vaadin pages in my app, with no difficulties, so it appears that Vaadin plays well with others, and can be introduced into an existing project that uses, for instance, a whack of JSP&#8217;s that one might want to obsolete.</p>
<p><b>Webapps</b><br />
I think Vaadin warrants more exploration, and I intend to put it further through its paces in the next few weeks. It appears extremely well-suited to web applications, as opposed to websites with a tiny bit of dynamic stuff in them. </p>
<p>It offers an interesting alternative to some of the patterns I&#8217;ve seen for advanced dynamic webapp development so far. </p>
<p>One approach I&#8217;ve seen a lot is to divide the duties of creating an app into the &#8220;back end&#8221; services and the &#8220;UI&#8221;. Generally the UI is written in either JavaScript, or uses Flex or some other semi-proprietary approach. The &#8220;back end&#8221; stuff is frequently written to expose it&#8217;s services as REST, then the two are bolted together. The pain point here happens when the two meet, as it&#8217;s common and easy to have minor (or major!) misunderstandings between the two teams. This usually results in a lot of to-and-fro to work out the differences before the app comes all the way to life.</p>
<p>The other approach, more common on smaller or resource-strapped teams, is to have the same group responsible for both UI and back-end services. This reduces the thrash in the joints a bit, but doesn&#8217;t eliminate it, because the two technologies on the two sides of the app aren&#8217;t the same. You can&#8217;t test JavaScript the same way you write Java, for instance, and they&#8217;re two different languages &#8211; one of which (Java) has far better tooling support than the other. IDE support, for instance, is superb for Java, and spotty at best for JavaScript.</p>
<p>With Vaadin, both of these approaches become unnecessary, as its the same technology all the way through (at least, what you write is &#8211; technically it&#8217;s still using JavaScript, but because that&#8217;s generated, I don&#8217;t count it).</p>
<p>You get to use all of the tools you know and love for the back-end services to write the code for the UI, which you can then unit and functional test to your heart&#8217;s content.</p>
<p>The temptation to mix concerns between UI code and back-end service code must still be resisted, of course, but at least that code isn&#8217;t buried somewhere in the middle of a JSP page, ready to leap out and bite you later.</p>
<p>Because you&#8217;re using dynamic layouts, the app always fits properly on the screen without any extra work, addressing a pet peeve of mine, the &#8220;skinny&#8221; webapp, restraining itself to the least common denominator of screen size, thus rendering impotent my nice wide monitors.</p>
<p><b>Scala</b><br />
Just because Vaadin is a Java library doesn&#8217;t restrict you to using Java to drive it, however. I made another little webapp where the whole UI was defined in Scala, calling the Vaadin APIs, and it worked like a charm. In some ways, Scala is an even better fit for Vaadin than straight Java, I suspect. I haven&#8217;t tried any other JVM compatible language, but I see no reason they wouldn&#8217;t work equally well.</p>
<p><b>Deployment and Development Cycle</b><br />
As I was building the app with Maven, I added a couple of lines to my POM and was able to say &#8220;mvn jetty:run&#8221; to get my Vaadin app up and running on my local box in a few seconds. My development cycle was only a few seconds between compile and interactive tests, as I was experimenting with the trial-and-error method. </p>
<p>TDD would be not only possible, but easy in this situation.</p>
<p>I successfully deployed my little Vaadin app to ServiceMix, my OSGi container of choice, without a hitch. </p>
<p>Performance appeared excellent overall, although I haven&#8217;t formally tested it with a load-testing tool (yet).</p>
<p><b>Summary</b><br />
So far, I&#8217;m impressed with Vaadin. I&#8217;m more impressed with any web framework I&#8217;ve worked with in a number of years, in fact. I&#8217;m sure there are some warts in there somewhere, but for the benefits it brings to the table, I suspect they&#8217;re easily worth it. I think the advantages to teams that already speak fluent Java is hard to overstate, and the productivity to produce good-looking and functioning webapps is quite remarkable.</p>
<p>Over the next few weeks I&#8217;ll push it a bit harder with a complex example application, and see how it stacks up against other web app technologies I&#8217;ve worked with in a more realistic scenario.</p>
<p>By: <a href="http://devblog.point2.com/author/michaelnash01/" target="_blank">Mike Nash</a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Scala でトレイトを使うべきか否か。]]></title>
<link>http://scova0731.wordpress.com/2009/11/22/scala-%e3%81%a7%e3%83%88%e3%83%ac%e3%82%a4%e3%83%88%e3%82%92%e4%bd%bf%e3%81%86%e3%81%b9%e3%81%8d%e3%81%8b%e5%90%a6%e3%81%8b%e3%80%82/</link>
<pubDate>Sun, 22 Nov 2009 05:30:44 +0000</pubDate>
<dc:creator>scova0731</dc:creator>
<guid>http://scova0731.wordpress.com/2009/11/22/scala-%e3%81%a7%e3%83%88%e3%83%ac%e3%82%a4%e3%83%88%e3%82%92%e4%bd%bf%e3%81%86%e3%81%b9%e3%81%8d%e3%81%8b%e5%90%a6%e3%81%8b%e3%80%82/</guid>
<description><![CDATA[スケーラブルプログラミングp.219から少し。 1「ふるまいが再利用されないような場合」なら、具象クラスにする。 2「複数の無関係なクラスで再利用される可能性がある」なら、トレイトにする。 3「Jav]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>スケーラブルプログラミングp.219から少し。</p>
<blockquote><p>1「ふるまいが再利用されないような場合」なら、具象クラスにする。</p>
<p>2「複数の無関係なクラスで再利用される可能性がある」なら、トレイトにする。</p>
<p>3「Javaコードを継承できるようにしたい場合」は、抽象クラスを使う。</p>
<p>4「ライブラリー」をコンパイル後の形態で配布したい場合」には、抽象クラスを使った方が良いかもしれない。(<em>外部でトレイトを継承しているクラスを使うと、トレイトのメンバー獲得／喪失時に外部側の再コンパイルが必要になる。</em>)</p>
<p>5「処理効率が非常に重視される場合」には、クラスを使った方が良いかもしれない。(<em>Javaはインタフェースよりクラスの方が速い。トレイトはインタフェースとしてコンパイルされるので、ややオーバーヘッドがかかる</em>)</p>
<p>6「以上を検討してみて、まだどちらが良いかはっきりしない場合」、まずトレイとにしてみるのが良いであろう。</p></blockquote>
<p>個人的に特に気をつけないとなと思ったのは、4でした。トレイトの使い方によっては<br />
、アプリの組み方ががらっと変わってきそうですね。</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[¿Cómo serían los lenguajes de programación si fueran personas?]]></title>
<link>http://paranoialabs.wordpress.com/2009/11/20/%c2%bfcomo-serian-los-lenguajes-de-programacion-si-fueran-personas/</link>
<pubDate>Sat, 21 Nov 2009 00:49:29 +0000</pubDate>
<dc:creator>luizja</dc:creator>
<guid>http://paranoialabs.wordpress.com/2009/11/20/%c2%bfcomo-serian-los-lenguajes-de-programacion-si-fueran-personas/</guid>
<description><![CDATA[Buscando hace un rato en mundogeek un manual de python (el cual recomiendo ampliamente) para crossov]]></description>
<content:encoded><![CDATA[Buscando hace un rato en mundogeek un manual de python (el cual recomiendo ampliamente) para crossov]]></content:encoded>
</item>
<item>
<title><![CDATA[String Distance and Refactoring in Scala]]></title>
<link>http://oldfashionedsoftware.com/2009/11/19/string-distance-and-refactoring-in-scala/</link>
<pubDate>Thu, 19 Nov 2009 05:19:04 +0000</pubDate>
<dc:creator>Matt</dc:creator>
<guid>http://oldfashionedsoftware.com/2009/11/19/string-distance-and-refactoring-in-scala/</guid>
<description><![CDATA[Here&#8217;s a three-for-one special for you: A post about implementing the Levenshtein string dista]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Here&#8217;s a three-for-one special for you: A post about implementing the Levenshtein string distance algorithm in Scala AND refactoring it from an imperative style to a functional style AND I even throw in a short lesson on memoization. To make sure that our refactoring is correct and preserves the expected behavior, I&#8217;ll unit test the code along the way using ScalaTest. ScalaCheck, JUnit, or TestNG would work just as well, but I used ScalaTest.</p>
<h2>First Things First</h2>
<p>&#8220;What, exactly,&#8221; some of you may be asking, &#8220;is Levenshtein string distance?  Some kind of Teutonic tailoring terminology?&#8221; Not at all.  It&#8217;s a way of measuring how alike or different two strings of symbols are.  For example, the string &#8220;sturgeon&#8221; is a lot more similar to &#8220;surgeon&#8221; than to &#8220;urgently&#8221;.  &#8220;Sturgeon&#8221; and &#8220;surgeon&#8221; are only a single letter (t) apart.  They have a string distance of 1.  &#8220;Sturgeon&#8221; and &#8220;urgently&#8221; share some letters, but each has some letters not present in the other.  So what&#8217;s their string distance?  It&#8217;s not so obvious now.</p>
<p>String distance is useful.  The use that most quickly springs to mind is spelling correction.  If I type &#8220;computwr&#8221; a string distance algoritm could tell us that &#8220;computwr&#8221; is very close to the dictionary word &#8220;computer&#8221;.  But there&#8217;s more to it than that.  There are a lot of fuzzy problems in which you want to find which two sets of complex data are most similar.  One way to solve a problem like that is to encode it into a string compare using string distance.  For example, you could write a program to find pen strokes in an image and encode their shapes (up, curve left, down, angle right, etc) as a string which could be compared to known encodings for handwritten letters.  By finding the closest matches you can create a handwriting recognition program.  String distance is useful in DNA analysis, of course, recognizing patterns in signals, and a host of other situations.</p>
<p>The Levenshtein string distance algorithm was developed by Vladimir Levenshtein in 1965.  It can easily tell us the distance from &#8220;sturgeon&#8221; to &#8220;urgently&#8221;.  This algorithm breaks down string transformation into three basic operations:  adding a character, deleting a character, and replacing a character.  Each of these operations is assigned a cost, usually a cost of 1 for each operation.  Leaving a character unchanged has a cost of 0.  So to go from &#8220;sturgeon&#8221; to &#8220;surgeon&#8221; you leave the &#8220;s&#8221; unchanged for a cost of 0.  Then you add a &#8220;t&#8221; for a cost of 1.  All the other letters also remained unchanged, so the total cost is 1, just as we expected.</p>
<p>To change &#8220;sturgeon&#8221; to &#8220;urgently&#8221; is harder.  They have the same number of letters, so we could just do a replacement on each one for a distance of 8.  But is that the shortest distance?  What if we try to re-use that &#8220;urge&#8221; from &#8220;sturgeon&#8221;?  Can we re-use the &#8220;n&#8221;?  Does that help?  What about the &#8220;t&#8221;?  We need an algorithm that we can follow.</p>
<h2>The Grid</h2>
<p>What we need is a way to find the cheapest combination of operations which changes the first string to the second.  That&#8217;s the Levenshtein algorithm.  It works like this.  Write the first string vertically from top to bottom.  To the right of each letter write 1, 2, 3, etc.  Write a 0 above the number 1.  Then write the second string horizontally and again add the numbers 1, 2, 3 etc. to the right of the 0.  It will look something like this:</p>
<pre class="brush: python;">
    u r g e n t l y
  0 1 2 3 4 5 6 7 8
s 1
t 2
u 3
r 4
g 5
e 6
o 7
n 8
</pre>
<p>That&#8217;s the first step.  The grid remains un-filled-in at this point.  Can you guess what the grid positions are going to hold?  They are going to hold the cost to convert the various prefixes of &#8220;sturgeon&#8221; to the various prefixes of &#8220;urgently&#8221;.  The position at the intersection of row r4, and the column a2, for example, will contain the cost to convert &#8220;stur&#8221; to &#8220;ur&#8221;.  We fill in these positions (left-to-right then top to bottom) with the smallest of the following three numbers:</p>
<ul>
<li>The number above the current position plus one.
<li>The number to the left of the current position plus one.
<li>The above-left number if row letter and column letter are the same, or the above-left number plus one otherwise.
</ul>
<p>When we finish, the bottom right corner contains the cost to convert the first string to the second.</p>
<h2>But Why?  (Understanding the Algorithm)</h2>
<p>Those are some shockingly simple rules!  Let&#8217;s examine how they translate into string distance.</p>
<p>First, what are those numbers 0 to n that we write along the top and left?  They&#8217;re not just indices.  The numbers along the top represent the cost to convert the empty string to the various prefixes of &#8220;urgently&#8221;.  The cost is 0 to convert &#8220;&#8221; to &#8220;&#8221;, 1 to convert &#8220;&#8221; to &#8220;u&#8221;, 2 to convert &#8220;&#8221; to &#8220;ur&#8221;, and so on.  The numbers on the left are the cost to convert the prefixes of &#8220;sturgeon&#8221; to the the empty string .  &#8220;&#8221; to &#8220;&#8221; is 0, &#8220;s&#8221; to &#8220;&#8221; is 1, and so forth.  These costs are obvious.  The only way to convert &#8220;&#8221; to &#8220;urgently&#8221; is to add eight letters.  There&#8217;s nothing to delete, nothing to replace.  The only way to convert &#8220;sturgeon&#8221; to &#8220;&#8221; is to delete all eight letters.</p>
<p>Each position, as we have established, represents the cost to convert the string of characters down the left side ending in the current row&#8217;s character into the the string of characters along the top ending at the current column&#8217;s character.  Put another way, for any given position let&#8217;s call the current row&#8217;s letter A, and the current column&#8217;s letter B.  If we use a colon (:) to indicate string concatenation then the beginning string, the one along the left of the grid, can be written Prefix1:A.  So for our example word &#8220;sturgeon&#8221; if we look at a position in row e6 then Prefix1 is &#8220;sturg&#8221; and the final letter, which we&#8217;re calling A, is &#8220;e&#8221;.</p>
<p>So, speaking in terms of Prefix1, Prefix2, A, and B, we use the following inputs:</p>
<ul>
<li>The cost to change Prefix1 to Prefix2:<b>B</b> (the number above the current position).
<li>The cost to change Prefix1:<b>A</b> to Prefix2 (the number to the left).
<li>The cost to change Prefix1 to Prefix2 (the above-left number).
</ul>
<p>If we know the costs of these three conversions we can find the cost to change Prefix1:A to Prefix2:B using this logic:</p>
<ul>
<li>We know that if converting Prefix1 to Prefix2:B has a cost of X, then Prefix1:A can be converted to Prefix2:B for the cost of X plus the cost of deleting A, or X + 1.
<li>We know that if converting Prefix1:A to Prefix2 has a cost of Y, then Prefix1:A can be converted to Prefix2:B for the cost of Y plus the cost of adding B, or Y + 1.
<li>We know that if converting Prefix1 to Prefix2 has a cost of Z, then Prefix1:A can be converted to Prefix2:B for the cost of Z plus the cost of replacing A with B, or Z + (0 or 1 depending on whether A = B).
</ul>
<p>If you understand the above logic, then you understand this really neat algorithm.  It&#8217;s a quintessential example of dynamic programming.  The solution is built up by solving simpler problems.  You start with the trivial case of converting to and from the empty string, and then you build up the solution for the prefixes until you have the complete solution.</p>
<p>In the grid&#8217;s initial configuration there is only one location for which we know all three costs and that is row s1, column u1.  That&#8217;s the only space for which all three neighboring values (above, left, and above-left) are populated.  After we fill in this one, there are two more spaces available to us.  Those are (t2, u1) and (s1, r2).  Ordinarily, though, the spaces are populated line by line.</p>
<h2>A Simple Example</h2>
<p>Let&#8217;s do a quick example by hand.  Then we&#8217;ll take a stab at implementing it in code.  What&#8217;s the string distance from &#8220;hat&#8221; to &#8220;tape&#8221;?  First, our empty grid:</p>
<pre class="brush: python;">
    t a p e
  0 1 2 3 4
h 1
a 2
t 3
</pre>
<p>The first space is row h, column t.  The letters are different so our choices are 1 + 1 (above), 1 + 1 (left), or 0 + 1 (above-left).  0 + 1 is the smallest value, so the first space gets populated with 1.  The next space has choices 2 + 1 (above), 1 + 1 (left), or 1 + 1 (above-left).  1 + 1 is the lowest, so we fill in the second space with 2.  Once we finish the row, we have this:</p>
<pre class="brush: python;">
    t a p e
  0 1 2 3 4
h 1 1 2 3 4
a 2
t 3
</pre>
<p>The next space is row a, column t.  Our choices are 1 + 1 (above), 2 + 1 (left), or 1 + 1 (above-left).  1 + 1 is the smallest value, so the space gets populated with 2.  The next space has choices 2 + 1 (above), 2 + 1 (left), or 1 + 0 (above-left).  Why 1 + 0?  Because the above-left value is 1 and both letters for this space are &#8220;a&#8221; so we can replace &#8220;a&#8221; with &#8220;a&#8221; for free.  Go ahead and finish the whole grid.  This is the result:</p>
<pre class="brush: python;">
    t a p e
  0 1 2 3 4
h 1 1 2 3 4
a 2 2 1 2 3
t 3 2 2 2 3
</pre>
<p>The strings &#8220;hat&#8221; and &#8220;tape&#8221; have a distance of 3.</p>
<h2>Some Code, Finally</h2>
<p>As fascinating as Levenshtein distance is, and as much more as there is to say on the topic, the time has come to write some code.  Here&#8217;s a Scala implementation that is very close to the pencil-and-paper approach that we just performed.</p>
<pre class="brush: python;">
import scala.Math.min
import scala.Math.max

object StringDistance {
  def stringDistance(s1: String, s2: String): Int = {
    def minimum(i1: Int, i2: Int, i3: Int) = min(min(i1, i2), i3)

    val dist = new Array[Array[Int]](s1.length + 1, s2.length + 1)

    for (idx &#60;- 0 to s1.length) dist(idx)(0) = idx
    for (jdx &#60;- 0 to s2.length) dist(0)(jdx) = jdx

    for (idx &#60;- 1 to s1.length; jdx &#60;- 1 to s2.length)
      dist(idx)(jdx) = minimum (
        dist(idx-1)(jdx  ) + 1,
        dist(idx  )(jdx-1) + 1,
        dist(idx-1)(jdx-1) + (if (s1(idx-1) == s2(jdx-1)) 0 else 1)
      )

    dist(s1.length)(s2.length)
  }
</pre>
<p>Do you see what I mean when I say it&#8217;s close to the pencil-and-paper approach?  We actually construct a two-dimensional Array to represent the grid we drew earlier.  It&#8217;s a very literal implementation.</p>
<p>To explain the code briefly, we declare a singleton StringDistance having a single method called stringDistance.  Within this method we declare a 3-argument minimum method. (I wonder why there&#8217;s no &#8220;def min(params: Int*): Int&#8221; defined in scala.Math.)  Then we create an array called &#8220;dist&#8221; and populate the top row and leftmost column in lines 8-11.  The for loop on line 13 cycles through each array position from left to right then top to bottom, and populates them according to the Levenshtein logic. Finally, once the grid is filled in we return the number in the bottom right position.</p>
<p>The job&#8217;s not done yet, of course.  We haven&#8217;t written our unit tests.  Here&#8217;s the test I wrote:</p>
<pre class="brush: python;">
import org.scalatest._

class StringDistanceSuite extends FunSuite with PrivateMethodTester {

  test(&#34;stringDistance should work on empty strings&#34;) {
    assert( StringDistance.stringDistance(   &#34;&#34;,    &#34;&#34;) == 0 )
    assert( StringDistance.stringDistance(  &#34;a&#34;,    &#34;&#34;) == 1 )
    assert( StringDistance.stringDistance(   &#34;&#34;,   &#34;a&#34;) == 1 )
    assert( StringDistance.stringDistance(&#34;abc&#34;,    &#34;&#34;) == 3 )
    assert( StringDistance.stringDistance(   &#34;&#34;, &#34;abc&#34;) == 3 )
  }

  test(&#34;stringDistance should work equal strings&#34;) {
    assert( StringDistance.stringDistance(   &#34;&#34;,    &#34;&#34;) == 0 )
    assert( StringDistance.stringDistance(  &#34;a&#34;,   &#34;a&#34;) == 0 )
    assert( StringDistance.stringDistance(&#34;abc&#34;, &#34;abc&#34;) == 0 )
  }

  test(&#34;stringDistance should work where only inserts are needed&#34;) {
    assert( StringDistance.stringDistance(   &#34;&#34;,   &#34;a&#34;) == 1 )
    assert( StringDistance.stringDistance(  &#34;a&#34;,  &#34;ab&#34;) == 1 )
    assert( StringDistance.stringDistance(  &#34;b&#34;,  &#34;ab&#34;) == 1 )
    assert( StringDistance.stringDistance( &#34;ac&#34;, &#34;abc&#34;) == 1 )
    assert( StringDistance.stringDistance(&#34;abcdefg&#34;, &#34;xabxcdxxefxgx&#34;) == 6 )
  }

  test(&#34;stringDistance should work where only deletes are needed&#34;) {
    assert( StringDistance.stringDistance(  &#34;a&#34;,    &#34;&#34;) == 1 )
    assert( StringDistance.stringDistance( &#34;ab&#34;,   &#34;a&#34;) == 1 )
    assert( StringDistance.stringDistance( &#34;ab&#34;,   &#34;b&#34;) == 1 )
    assert( StringDistance.stringDistance(&#34;abc&#34;,  &#34;ac&#34;) == 1 )
    assert( StringDistance.stringDistance(&#34;xabxcdxxefxgx&#34;, &#34;abcdefg&#34;) == 6 )
  }

  test(&#34;stringDistance should work where only substitutions are needed&#34;) {
    assert( StringDistance.stringDistance(  &#34;a&#34;,   &#34;b&#34;) == 1 )
    assert( StringDistance.stringDistance( &#34;ab&#34;,  &#34;ac&#34;) == 1 )
    assert( StringDistance.stringDistance( &#34;ac&#34;,  &#34;bc&#34;) == 1 )
    assert( StringDistance.stringDistance(&#34;abc&#34;, &#34;axc&#34;) == 1 )
    assert( StringDistance.stringDistance(&#34;xabxcdxxefxgx&#34;, &#34;1ab2cd34ef5g6&#34;) == 6 )
  }

  test(&#34;stringDistance should work many operations are needed&#34;) {
    assert( StringDistance.stringDistance(&#34;example&#34;, &#34;samples&#34;) == 3 )
    assert( StringDistance.stringDistance(&#34;sturgeon&#34;, &#34;urgently&#34;) == 6 )
    assert( StringDistance.stringDistance(&#34;levenshtein&#34;, &#34;frankenstein&#34;) == 6 )
    assert( StringDistance.stringDistance(&#34;distance&#34;, &#34;difference&#34;) == 5 )
    assert( StringDistance.stringDistance(&#34;java was neat&#34;, &#34;scala is great&#34;) == 7 )
  }

}
</pre>
<p>It tests several special cases as well as the general case.  All we have to do is compile our StringDistance object and the StringDistanceSuite unit test, fire up the scala interpreter and run the test:</p>
<pre class="brush: python;">
scala&#62; (new StringDistanceSuite).execute()
Test Starting - StringDistanceSuite: recursiveStringDistance should work on empty strings
Test Succeeded - StringDistanceSuite: recursiveStringDistance should work on empty strings
Test Starting - StringDistanceSuite: recursiveStringDistance should work on equal strings
Test Succeeded - StringDistanceSuite: recursiveStringDistance should work on equal strings
Test Starting - StringDistanceSuite: recursiveStringDistance should work where only inserts are needed
Test Succeeded - StringDistanceSuite: recursiveStringDistance should work where only inserts are needed
Test Starting - StringDistanceSuite: recursiveStringDistance should work where only deletes are needed
Test Succeeded - StringDistanceSuite: recursiveStringDistance should work where only deletes are needed
Test Starting - StringDistanceSuite: recursiveStringDistance should work where only substitutions are needed
Test Succeeded - StringDistanceSuite: recursiveStringDistance should work where only substitutions are needed
Test Starting - StringDistanceSuite: stringDistance should work many operations are needed
Test Succeeded - StringDistanceSuite: stringDistance should work many operations are needed

scala&#62;
</pre>
<h2>Refactoring: Reduced Memory Usage</h2>
<p>The code passes all the tests, so let&#8217;s take things a step further.  One shortcoming of our implementation is that it can require a lot of memory.  That array has to be of size (n+1)*(m+1) where n and m are the lengths of the two strings we&#8217;re comparing.  If you want to apply the method to strings that are a few hundred characters long (or longer) then you&#8217;re starting to talk about some serious memory requirements.  How can we reduce the amount of memory required?  Can you think of a way?</p>
<p>Once we complete one row of the grid, we use it again as an input when we compute the next row.  But after that we&#8217;re done with it.  Why leave it to clutter the heap?  Let&#8217;s tweak our implementation slightly.  Try rewriting the method using only two rows.  Fill the first row with the initial 0, 1, 2, etc.  Then use one to compute the other over and over.  Think about how you would implement this, then have a look at my solution below.</p>
<pre class="brush: python;">
  def stringDistance(s1: String, s2: String): Int = {
    def minimum(i1: Int, i2: Int, i3: Int) = min(min(i1, i2), i3)

    var dist = ( new Array[Int](s1.length + 1),
                 new Array[Int](s1.length + 1) )

    for (idx &#60;- 0 to s1.length) dist._2(idx) = idx

    for (jdx &#60;- 1 to s2.length) {
      val (newDist, oldDist) = dist
      newDist(0) = jdx
      for (idx &#60;- 1 to s1.length) {
        newDist(idx) = minimum (
          oldDist(idx) + 1,
          newDist(idx-1) + 1,
          oldDist(idx-1) + (if (s1(idx-1) == s2(jdx-1)) 0 else 1)
        )
      }
      dist = dist.swap
    }

    dist._2(s1.length)
  }
</pre>
<p>This one uses a Pair (also called a Tuple2) containing two one-dimensional arrays, instead of a 2*(n+1) array.  Pair happens to have the very handy &#8220;swap&#8221; method which we can use to trade out the rows when we&#8217;ve finished one and are ready to compute the next.</p>
<p>This is where our unit tests really show their worth. No need to wonder whether this new code really does work.  We just recompile, run the tests again, and we can see that the code still gives us the expected results.</p>
<h2>Refactoring: Recursion, Kind Of</h2>
<p>What are some other ways we could write this code?  Can it be improved?  I thought I would try to replace the iteration in the previous implementations with recursion.  Here&#8217;s what that code looks like:</p>
<pre class="brush: python;">
  def stringDistance(s1: String, s2: String): Int = {
    def newCost(ins: Int, del: Int, subst: Int, c1: Char, c2:Char) =
      Math.min( Math.min( ins+1, del+1 ), subst + (if (c1 == c2) 0 else 1) )

    def getNewCosts(s1: List[Char], c2: Char, delVal: Int, prev: List[Int] ): List[Int] = (s1, prev) match {
      case (c1 :: _ , substVal :: insVal :: _) =&#62;
        delVal :: getNewCosts(s1.tail, c2, newCost(insVal, delVal, substVal, c1, c2), prev.tail)
      case _ =&#62; List(delVal)
    }

    def sd(s1: List[Char], s2: List[Char], prev: List[Int]): Int = s2 match {
      case Nil =&#62; prev.last
      case _ =&#62; sd( s1, s2.tail, getNewCosts(s1, s2.head, prev.head+1, prev) )
    }

    (s1, s2) match {
      case (`s2`, `s1`) =&#62; 0
      case (_, &#34;&#34;) &#124; (&#34;&#34;, _) =&#62; max(s1.length, s2.length)
      case _ =&#62; sd(s1.toList, s2.toList, (0 to s1.length).toList)
    }
  }
</pre>
<p>It&#8217;s a pretty naïve implementation, actually.  It just replaces the the repetition of the two for loops with the repetition of the recursion of the two methods sd and getNewCosts.  The sd method is even tail-recursive, allowing scala to optimize it.  It does the same basic thing as the for loop version, though.  It recurses through the characters of a row in the getNewCosts method, and it recurses through the rows of the grid in the sd method.</p>
<p>It looks more complicated than the previous implementations.  It&#8217;s harder to read.  But it passes our unit tests, so we can be pretty sure it&#8217;s correct.</p>
<h2>Refactoring: List Methods</h2>
<p>After the last implementation, I thought it looked a little sloppy.  I wondered whether I could improve the situation by using some of the many useful methods built into scala&#8217;s List class.  Here is the comparatively brief code that resulted:</p>
<pre class="brush: python;">
  def stringDistance(s1: String, s2: String): Int = {
    def sd(s1: List[Char], s2: List[Char], costs: List[Int]): Int = s2 match {
      case Nil =&#62; costs.last
      case c2 :: tail =&#62; sd( s1, tail,
          (List(costs.head+1) /: costs.zip(costs.tail).zip(s1))((a,b) =&#62; b match {
            case ((rep,ins), chr) =&#62; Math.min( Math.min( ins+1, a.head+1 ), rep + (if (chr==c2) 0 else 1) ) :: a
          }).reverse
        )
    }
    sd(s1.toList, s2.toList, (0 to s1.length).toList)
  }
</pre>
<p>Like I say, it&#8217;s brief.  Those List methods give you a lot of mileage.  </p>
<h2>Refactoring: Real Recursion</h2>
<p>The more I looked at my previous attempt at a recursive solution, the more I realized how hare-brained it was.  It wasn&#8217;t <i>real</i> recursion.  It was just iteration using the stack.  So I went back to the drawing board.  If I want to know the final answer, the value in the bottom right position, how do I get it?  I apply my three rules to the above, left, and above-left positions.  How do I get those positions?  Apply the rules again.  That&#8217;s real recursion.  Here&#8217;s my first stab at it:</p>
<pre class="brush: python;">
  def stringDistance(s1: String, s2: String): Int = {
    def min(a:Int, b:Int, c:Int) = Math.min( Math.min( a, b ), c)
    def sd(s1: List[Char], s2: List[Char]): Int = (s1, s2) match {
      case (_, Nil) =&#62; s1.length
      case (Nil, _) =&#62; s2.length
      case (c1::t1, c2::t2)  =&#62; min( sd(t1,s2) + 1, sd(s1,t2) + 1,
                                     sd(t1,t2) + (if (c1==c2) 0 else 1) )
    }
    sd( s1.toList, s2.toList )
  }
</pre>
<p>Now, THAT is a nice looking recursive function.  That&#8217;s more like it.  See the pattern match block?  If we try to convert from any string to the empty string or from the empty to a non-empty string then we just use the string length.  You see?  That takes care of the positions along the top and left of the grid.  All the others are determined in the last case.  That last case just applies our three rules.  That is so short and simple.  It&#8217;s a thing of beauty.</p>
<p>The only problem?  It doesn&#8217;t work.</p>
<p>It&#8217;s technically correct.  It will return correct answers &#8230; eventually.  Or, rather, I think it will.  I can&#8217;t be sure because it&#8217;s too slow to complete my unit tests! For anything but very short inputs (4 or 5 characters), the function takes a long time to return.  Why?  Let&#8217;s look at how many recursive calls are made for some inputs.</p>
<p>If we pass use strings &#8220;a&#8221; and &#8220;b&#8221; we pass by the &#8220;(_, Nil)&#8221; and &#8220;(Nil, _)&#8221; cases in the first call to function sd, because both our strings (Lists, actually) are non-empty.  This results in three more calls to sd.  Each of these three calls includes an empty List of characters, so there is no more recursion.  That&#8217;s a total of four calls to sd for strings &#8220;a&#8221; and &#8220;b&#8221;.</p>
<p>What about &#8220;ab&#8221; and &#8220;xy&#8221;?  Think about it for a moment?  Step through the function in your head.  How many calls to sd will there be for &#8220;ab&#8221; and &#8220;xy&#8221;?</p>
<p>Have you done it?  I count 19.  What about &#8220;abc&#8221; and &#8220;xyz&#8221;?  I&#8217;ll save you the trouble.  It&#8217;s 94.  For length 4 strings it&#8217;s 481.  For length 5 it&#8217;s 2524.  Length 6 is 13,483.  Then 73 thousand, then 400 thousand, then 2 million and so forth.  Why so many calls?  Each position in the grid is computed using all the positions to the left and all the positions above the current position.  So a position in the top left will be computed and recomputed many times.</p>
<p>There is a way to get around this, of course.  You probably already have some ideas.  We&#8217;re going to do something called memoization.  When you memoize a function, you make it remember results that it computed previously without having to actually recompute them.  I&#8217;ll do that by caching results in a map.  The map&#8217;s key is a Pair of List[Char]s, the inputs to my inner function sd, and its data is an Int, the return type of sd.  I will modify sd to first check the map to see if the result for the current parameters has already been cached.  If so, we simply return it.  If not, we compute the value, cache it, and return it.</p>
<pre class="brush: python;">
  def stringDistance(s1: String, s2: String): Int = {
    val memo = scala.collection.mutable.Map[(List[Char],List[Char]),Int]()
    def min(a:Int, b:Int, c:Int) = Math.min( Math.min( a, b ), c)
    def sd(s1: List[Char], s2: List[Char]): Int = {
      if (memo.contains((s1,s2)) == false)
        memo((s1,s2)) = (s1, s2) match {
          case (_, Nil) =&#62; s1.length
          case (Nil, _) =&#62; s2.length
          case (c1::t1, c2::t2)  =&#62; min( sd(t1,s2) + 1, sd(s1,t2) + 1,
                                         sd(t1,t2) + (if (c1==c2) 0 else 1) )
        }
      memo((s1,s2))
    }

    sd( s1.toList, s2.toList )
  }
}
</pre>
<p>There.  That uglies up my function somewhat, but at least it&#8217;s usable now.  And it passes my unit tests, so I&#8217;m reasonably assured that it&#8217;s right.</p>
<p>Memoization only works if you expect the same result for each identical function call.  If your function takes input from stdin, for example, you can&#8217;t memoize that.  Or if it has a random component.  Or if, for any other reason, its return value is not always the same for the same inputs.  You can memoize functions in different ways.  There&#8217;s a post on <a href="http://michid.wordpress.com/2009/02/23/function_mem/">Michid&#8217;s Weblog</a> about a more general solution, a memoizing class which wraps existing functions to give you a memoized version.  </p>
<h2>PHEW!</h2>
<p>Ok, I&#8217;ve tried to keep my rambling to a minimum in this post but it&#8217;s still a doozy.  The things I wanted to get across are:</p>
<ul>
<li>The usefulness of Levenshtein distance in solving a variety of problems.
<li>How to understand the Levenshtein distance algorithm and why it works.
<li>How to use unit tests to improve your code while maintaining some assurance that the new code still has the correct behavior.
<li>Some of the different ways of implementing Levenshtein.
</ul>
<p>In the end, I think I like the second implementation (the one that switches out the two rows) and the last implementation the best.  The second one seems to have good performance.  I did some informal performance tests and it has a good mix of performance and simplicity.  The last one, the memoized recursive one, appeals to me because it is in a more functional style and still has respectable performance.</p>
<p>
<p style="text-align:right;font-family:Times;">Don&#8217;t forget to <a href="http://oldfashionedsoftware.com/feed/rss"><img src="http://oldfashionedsoftware.com/files/2008/08/rssbutton.png"> subscribe to my RSS feed</a>, or <a href="http://twitter.com/mmofsoftware"><img src="http://oldfashionedsoftware.com/files/2009/08/twitter.png"> follow this blog on Twitter</a>.<br />Copyright © 2009 Matthew Jason Malone</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Frenzy Fixtures in Scala]]></title>
<link>http://lizdouglass.wordpress.com/2009/11/18/frenzy-fixtures-in-scala/</link>
<pubDate>Wed, 18 Nov 2009 11:52:10 +0000</pubDate>
<dc:creator>lizdouglass</dc:creator>
<guid>http://lizdouglass.wordpress.com/2009/11/18/frenzy-fixtures-in-scala/</guid>
<description><![CDATA[Following on from my post about Friday Feedback Frenzies, Mark, Ben and I looked at how to work out ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Following on from my post about <a href="http://lizdouglass.wordpress.com/2009/11/16/friday-feedback-frenzies/">Friday Feedback Frenzies</a>, <a href="www.markhneedham.com/blog/">Mark</a>, Ben and I looked at how to work out frenzy pairs. The idea with the frenzies is that you exchange feedback with two people each week, and that you rotate the people that you do this with. When I have organised these previously I have generally just picked people at random. Mark, Ben and I decided to generate a frenzy fixture (if you will).</p>
<p>Mark came up with the idea of using something like a football/tennis game scheduling algorithm. We found a <a href="http://www.devenezia.com/javascript/article.php/RoundRobin2.html">Round Robin cyclic algorithm</a> to get us started. Our first step was to get this algorithm working in Scala:</p>
<pre>      val numberOfPlayers = 12
      for (round &#60;- 1 to 11) {
        for (court &#60;- 1 to 6) {
          print((if(court == 1) 1 else (round + court - 2) % (numberOfPlayers - 1) + 2),
                (numberOfPlayers - 1 + round - court) % (numberOfPlayers - 1) + 2)
        }
        println()
      }</pre>
<p>The output from this is below. Each row represents a round and each bracketed pair in a row represents a match-up of two players on a court.</p>
<pre>(1,2)(3,12)(4,11)(5,10)(6,9)(7,8)
(1,3)(4,2)(5,12)(6,11)(7,10)(8,9)
(1,4)(5,3)(6,2)(7,12)(8,11)(9,10)
(1,5)(6,4)(7,3)(8,2)(9,12)(10,11)
(1,6)(7,5)(8,4)(9,3)(10,2)(11,12)
(1,7)(8,6)(9,5)(10,4)(11,3)(12,2)
(1,8)(9,7)(10,6)(11,5)(12,4)(2,3)
(1,9)(10,8)(11,7)(12,6)(2,5)(3,4)
(1,10)(11,9)(12,8)(2,7)(3,6)(4,5)
(1,11)(12,10)(2,9)(3,8)(4,7)(5,6)
(1,12)(2,11)(3,10)(4,9)(5,8)(6,7)</pre>
<p>Next we moved from everything being 1 indexed to being 0 indexed. We also changed the fixed player, who always plays on court 0, to be the last one in the player list. This was done only because it made the loops more readable:</p>
<pre>      val numberOfPlayers = 12
      for (round &#60;- 0 to 10) {
        for (court &#60;- 0 to numberOfPlayers/2 - 1) {
          print(((if(court == 0) numberOfPlayers - 1 else (court + round) % (numberOfPlayers - 1))),
                (((numberOfPlayers - 1) - court + round) % (numberOfPlayers - 1)))
        }
        println()
      }</pre>
<p>Then the output was:</p>
<pre>(11,0)(1,10)(2,9)(3,8)(4,7)(5,6)
(11,1)(2,0)(3,10)(4,9)(5,8)(6,7)
(11,2)(3,1)(4,0)(5,10)(6,9)(7,8)
(11,3)(4,2)(5,1)(6,0)(7,10)(8,9)
(11,4)(5,3)(6,2)(7,1)(8,0)(9,10)
(11,5)(6,4)(7,3)(8,2)(9,1)(10,0)
(11,6)(7,5)(8,4)(9,3)(10,2)(0,1)
(11,7)(8,6)(9,5)(10,4)(0,3)(1,2)
(11,8)(9,7)(10,6)(0,5)(1,4)(2,3)
(11,9)(10,8)(0,7)(1,6)(2,5)(3,4)
(11,10)(0,9)(1,8)(2,7)(3,6)(4,5)</pre>
<p>Our next step was to switch domains from sports to feedback frenzies:</p>
<pre>val participants = 12
val weeks = 10
for (frenzy &#60;- 0 until weeks) {
  for (pair &#60;- 0 until participants/2) {
    print(((if(pair == 0) participants - 1 else (pair + frenzy) % (participants - 1))),
          (((participants - 1) - pair + frenzy) % (participants - 1)))
  }
  println()
}</pre>
<p>Then we changed to creating a collection of all the pairs:</p>
<pre>      val participants = 12
      val weeks = 10
      val frenzyPairs = for {
        frenzy &#60;- 0 until weeks
        pair &#60;- 0 until participants/2
      } yield (((if(pair == 0) participants - 1 else (pair + frenzy) % (participants - 1))),
                (((participants - 1) - pair + frenzy) % (participants - 1)))
      frenzyPairs.foreach(print)
    }</pre>
<p>And the output&#8230;</p>
<pre>RangeM((11,0), (1,10), (2,9), (3,8), (4,7), (5,6))
RangeM((11,1), (2,0), (3,10), (4,9), (5,8), (6,7))
RangeM((11,2), (3,1), (4,0), (5,10), (6,9), (7,8))
RangeM((11,3), (4,2), (5,1), (6,0), (7,10), (8,9))
RangeM((11,4), (5,3), (6,2), (7,1), (8,0), (9,10))
RangeM((11,5), (6,4), (7,3), (8,2), (9,1), (10,0))
RangeM((11,6), (7,5), (8,4), (9,3), (10,2), (0,1))
RangeM((11,7), (8,6), (9,5), (10,4), (0,3), (1,2))
RangeM((11,8), (9,7), (10,6), (0,5), (1,4), (2,3))
RangeM((11,9), (10,8), (0,7), (1,6), (2,5), (3,4))</pre>
<p>As Ben quite rightly pointed out if we take two rows a time, then each person will exchange feedback with two people in the same frenzy. Our final step was to group each pair of successive rows. To do this we first moved to having two nested for loops. We thought that this would make it easier to do the grouping, but it ended up being redundant. Here our final version of the frenzy fixture generator:</p>
<pre>      val participants = 12
      val rounds = 10
      val frenzyPairs = for (frenzy &#60;- 0 until rounds)
                      yield for(pair &#60;- 0 until participants/2)
                            yield (((if(pair == 0) participants - 1 else (pair + frenzy) % (participants - 1))),
                                  (((participants - 1) - pair + frenzy) % (participants - 1)))

      val (evenOnes,oddOnes) = frenzyPairs.toList.zipWithIndex.partition(_._2%2 == 0)
      evenOnes.zip(oddOnes).foreach(println)</pre>
<p>Our final output was:</p>
<pre>((RangeM((11,0), (1,10), (2,9), (3,8), (4,7), (5,6)),0),(RangeM((11,1), (2,0), (3,10), (4,9), (5,8), (6,7)),1))
((RangeM((11,2), (3,1), (4,0), (5,10), (6,9), (7,8)),2),(RangeM((11,3), (4,2), (5,1), (6,0), (7,10), (8,9)),3))
((RangeM((11,4), (5,3), (6,2), (7,1), (8,0), (9,10)),4),(RangeM((11,5), (6,4), (7,3), (8,2), (9,1), (10,0)),5))
((RangeM((11,6), (7,5), (8,4), (9,3), (10,2), (0,1)),6),(RangeM((11,7), (8,6), (9,5), (10,4), (0,3), (1,2)),7))
((RangeM((11,8), (9,7), (10,6), (0,5), (1,4), (2,3)),8),(RangeM((11,9), (10,8), (0,7), (1,6), (2,5), (3,4)),9))</pre>
<p>The end result could be tidied up a little but it does provide us with a frenzy fixture for a given number of participants. Given more time we would have used names for participants rather than just numbers.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Review: The Dodos at The Scala]]></title>
<link>http://anikainlondon.wordpress.com/2009/11/18/review-the-dodos-at-the-scala/</link>
<pubDate>Wed, 18 Nov 2009 00:54:28 +0000</pubDate>
<dc:creator>anikainlondon</dc:creator>
<guid>http://anikainlondon.wordpress.com/2009/11/18/review-the-dodos-at-the-scala/</guid>
<description><![CDATA[Before Sam Francisco three piece The Dodos played, North Carolinian three piece MEGAFAUN played (no ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p style="text-align:justify;"><img class="alignleft" src="http://farm3.static.flickr.com/2579/4107022697_ecaaa89db3.jpg" alt="" width="500" height="333" />Before Sam Francisco three piece The Dodos played, North Carolinian three piece MEGAFAUN played (no reason for the shouty caps other than it makes their name even cooler than it all ready is).</p>
<p style="text-align:justify;">They all had good facial hair and their music was just as great. They were cheerful, endearing, energetic&#8230; I would most certainly recommend catching them if you can. They have the harmonies of Fleet Foxes but with some real foot stomping fun. For one song they departed from the stage (all three of them!) and did a little dance. It was brilliant. Check them out <a href="http://www.myspace.com/megafaun">here</a>.</p>
<p style="text-align:justify;">Then it was time for The Dodos. I had to miss them at End of the Road due to a clash with Neko Case (who was incredible) and in early September because I was at The Antlers (who were incredible) but I had seen them a year earlier supporting Okkervil River. I really enjoyed this particular show at Scala; Meric Long, the singer, puts so much energy into his performance and drummer Logan Kroeber, was fantastic. There was a especially lovely introduction to <em>Fools</em> using bows against the vibraphone. The crowd loved it and they returned for two encores&#8230; the place looked pretty sold out. My only complaint reflects my general feeling about most of the Dodos&#8217; material, sometimes their songs just feel like they go on a bit long without developing. But that&#8217;s not to say I think they&#8217;re very talented and put on a brilliant live performance. A good band more than worth checking out. They are touring in support of their 2009 release Time To Die. Here is their <a href="http://www.myspace.com/thedodos">Myspace</a>.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Writing a BDD DSL in Scala]]></title>
<link>http://cesarioramos.wordpress.com/2009/11/17/writing-a-bdd-dsl-in-scala/</link>
<pubDate>Tue, 17 Nov 2009 22:24:44 +0000</pubDate>
<dc:creator>cesarioramos</dc:creator>
<guid>http://cesarioramos.wordpress.com/2009/11/17/writing-a-bdd-dsl-in-scala/</guid>
<description><![CDATA[One of my favourite BDD frameworks is easyb. I really like the dsl for user stories. In a previous p]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>One of my favourite BDD frameworks is <a href="http://www.easyb.org/">easyb</a>. I really like the dsl for user stories. In a previous post called <a href="http://cesarioramos.wordpress.com/2008/03/26/easy-requirements-by-example/">Easy Requirements by Example</a> I discussed how easy and clear this dsl can be.</p>
<p>For Scala I would also like to have a dsl just like the one of easyb. Writing a dsl in Scala is real easy, not as easy as in Groovy, but easy enough. So I decided to see how fast I could write a story dsl in Scala.</p>
<p>So, I need to be able to write things like the following</p>
<pre class="brush: scala;">
   given (&#34;a blogger with a blog&#34;) {
    	val blogger = new Blogger(&#34;Mr Blog&#34;, &#34;mrblog@blogger.com&#34;, &#34;passwd&#34;)
    	val blog = new Blog(&#34;blogTitle&#34;, blogger)

		when(&#34;mr blog writes a new post&#34;) {
			blog addPost (&#34;post Title&#34;, &#34;post Text&#34;);
		}
		and
		when(&#34;mr blog publishes its post&#34;) {
		    blog publishPost
		}
		then(&#34;the post should be publised for reading&#34;) {
			blog.published shouldHave &#34;post Title&#34;
		}
	  }
</pre>
<p>The words <strong>given</strong>, <strong>when</strong>, <strong>then</strong>, <strong>and</strong>, <strong>shouldHave</strong> are part of the dsl.<br />
The story dsl words are defined by a curried function. They have a explaining piece of text as the first argument and a code block as the second argument.</p>
<p>See below the definition of <strong>given</strong></p>
<pre class="brush: scala;">
  def given(text: String)( codeBlock: =&#62; Unit ) = {
	  codeBlock;
  }
</pre>
<p>Because <strong>given</strong> is a curried function you can pass in the arguments one at a time. And when you pass in one argument you can choose to use curly braces instead of parentheses. As you can see in the above example, the <strong>given</strong> function has the rest of the story as the second argument within curly braces. So, the <strong>when</strong>, <strong>then</strong>, <strong>and</strong> form the codeBlock argument.</p>
<p>Here is the definition of the other methods</p>
<pre class="brush: scala;">
  def then(text: String)( codeBlock: =&#62; Unit ) = {
    codeBlock;
  }

  def when(text: String)( codeBlock: =&#62; Unit ) = {
    codeBlock;
  }

  def and(text: String)() = {
  }
</pre>
<p>&#8230; Yep this is really simple!</p>
<p>Because the codeBlock parameters are so-called &#8220;By-name-parameters&#8221; the codeBlocks of the functions are only evaluated when the <strong>given</strong> method evaluates it&#8217;s codeBlock! Also because closures in Scala see changes made to the free variables outside of the closure itself, you get the sequential execution ordering of the story.</p>
<p>The only thing that is left is the <strong>shouldHave</strong> word. As you might have guessed this is just a simple implicit conversion. To have free integration with IDE&#8217;s and other tools I choose to use JUnit as the underlying framework. So all the dsl vertification words are mapped to JUnit asserts as you can see below.</p>
<pre class="brush: scala;">

  implicit def shouldHave(l: List[Any]) = {
	  ShouldHave(l)
  }

case class ShouldHave(i: List[Any]) {
    def shouldHave(j: Any) = {
    	assertEquals(j, i.find( _ == j))
    }
}
</pre>
<p>You can use the dsl in your JUnit test like this</p>
<pre class="brush: scala;">[/sourcecode]
  @Test
  def bloggerSpecification() = {

    given (&#34;a blogger with a blog&#34;) {
      .....
    }
   }
[sourcecode]</pre>
<p>You can imagine that you would like to execute a story multiple times with different argument values. Lets say that you would like to execute the story with multiple post titles. A little extension of the dsl made that possible. I introduced the words <strong>testcases</strong>, <strong>addCase</strong> and <strong>execute_testcases_with_specification</strong>.<br />
See below an example</p>
<pre class="brush: scala;">
    testcases {
    	var postTitle: String = null;

    	addCase { postTitle = &#34;title 1&#34;	}
    	addCase { postTitle = &#34;title 2&#34;	}

    	execute_testcases_with_specification {
    		given (&#34;a blogger with a blog&#34;) {
    			val blogger = new Blogger(&#34;Mr Blog&#34;, &#34;mrblog@blogger.com&#34;, &#34;passwd&#34;)
    			val blog = new Blog(&#34;blogTitle&#34;, blogger)		   

    			when (&#34;mr blog writes a new post&#34;) {
    				blog addPost (postTitle, &#34;post Text&#34;);
    			}
    			and
    			when (&#34;mr blog publishes its post&#34;) {
    				blog publishPost
    			}
    			then (&#34;the post should be publised fo reading&#34;) {
    				blog.published exists(_.title == postTitle) shouldBe true
    			}
    		}
    	}
 </pre>
<p>What you see is that there are two test cases, each specifying a different value for the postTitle. The story is executed for each test case where the free variables are changed according to the test case at hand.</p>
<p>In order to make this work I stored all the test cases in a list. Then for each test case I first evaluate the test case. This sets the free variables of the story closure. Next I evaluate the story itself.</p>
<p>Again the code is really simple as you can see below.</p>
<pre class="brush: scala;">
object TestCase {

  var codeBlocks = List[() =&#62; Unit]()
  var scenario: Any = 0;

  def addCase( codeBlock: =&#62; Unit) = {
	  codeBlocks = codeBlock _ :: codeBlocks
  }

  def execute_testcases_with_specification( scenario: =&#62; Unit) = {
    codeBlocks.foreach( codeBlock =&#62; {
      codeBlock();
      scenario;
    })
  }

  def testcases( codeBlock: =&#62; Unit) = {
	  codeBlock
  }
}
</pre>
<p>If you made it this far in the post&#8230; what do you think of this approach?</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Scala and ldap]]></title>
<link>http://jgoday.wordpress.com/2009/11/16/scala-and-ldap/</link>
<pubDate>Mon, 16 Nov 2009 21:18:16 +0000</pubDate>
<dc:creator>jgoday</dc:creator>
<guid>http://jgoday.wordpress.com/2009/11/16/scala-and-ldap/</guid>
<description><![CDATA[Playing around with Scala, a very nice jvm language!, found Lift (web framework), looks simple and f]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Playing around with <a href="http://www.scala-lang.org/">Scala</a>, a very nice jvm language!,<br />
found <a href="http://liftweb.net/">Lift (web framework)</a>,<br />
looks simple and funny !</p>
<p>I was looking for ldap authentication with lift,<br />
i wasn&#8217;t able to find nothing <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> . </p>
<p>So i started to play with it,<br />
Here, I install an openldap server and some simple scala code to play with it.</p>
<ul>
<li>
<strong>Install openldap and some sample data (using arch linux)</strong></p>
<div style="border:1px dotted #909090;background-color:#f7f7f7;overflow:auto;padding:4px;">
<pre>
<code>
1- sudo pacman -S openldap
2- slappasswd -h {MD5} -s password (generates ldap password to use it later in config and user ldif file)
   {MD5}X03MO1qnZdYdgyfeuILPmQ==
</code></pre>
</div>
</li>
<li>
        <strong>Generate the ldap structure</strong> in initial_structure.ldif file</p>
<div style="border:1px dotted #909090;background-color:#f7f7f7;overflow:auto;padding:4px;">
<pre>
<code>
dn: dc=company,dc=com
dc: company
description: LDAP Main object
objectClass: organization
objectClass: dcObject
o: company.com

dn: ou=Users,dc=company,dc=com
ou: Users
objectClass: organizationalUnit

dn: ou=Groups,dc=company,dc=com
ou: Groups
objectClass: top
objectClass: organizationalUnit

dn: cn=main_group,ou=Groups,dc=company,dc=com
gidNumber: 2000
objectClass: posixGroup
objectClass: top
cn: main_group

dn: cn=secondary_group,ou=Groups,dc=company,dc=com
gidNumber: 2001
objectClass: posixGroup
objectClass: top
cn: secondary_group
</code></pre>
</div>
</li>
<li>
        <strong>Configure ldap server</strong> in /etc/openldap/slapd.conf</p>
<div style="border:1px dotted #909090;background-color:#f7f7f7;overflow:auto;padding:4px;">
<pre>
<code>
include         /etc/openldap/schema/core.schema
include         /etc/openldap/schema/cosine.schema
include         /etc/openldap/schema/courier.schema
include         /etc/openldap/schema/inetorgperson.schema
include         /etc/openldap/schema/nis.schema

allow bind_v2
password-hash {md5}

pidfile   /var/run/slapd.pid
argsfile  /var/run/slapd.args

database        bdb
suffix          "dc=company,dc=com"
rootdn          "cn=admin,dc=company,dc=com"
rootpw          {MD5}X03MO1qnZdYdgyfeuILPmQ==

directory       /var/lib/openldap/openldap-data
index   objectClass     eq
index   uid     eq
</code></pre>
</div>
</li>
<li>
        <strong>Populate initial ldap structure</strong></p>
<div style="border:1px dotted #909090;background-color:#f7f7f7;overflow:auto;padding:4px;">
<pre>
<code>
sudo /usr/sbin/slapadd -l initial_structure.ldif
</code></pre>
</div>
</li>
<li>
        <strong>Populate user and group data</strong>, for example in file users.ldif</p>
<div style="border:1px dotted #909090;background-color:#f7f7f7;overflow:auto;padding:4px;">
<pre>
<code>
dn: uid=sample_user_1,ou=Users,dc=company,dc=com
objectClass: top
objectClass: person
objectClass: organizationalPerson
objectClass: inetOrgPerson
objectClass: posixAccount
objectClass: shadowAccount
uid: sample_user_1
cn: Test User
sn: User
givenName: Test
userPassword: {MD5}X03MO1qnZdYdgyfeuILPmQ==
loginShell: /bin/bash
uidNumber: 10000
gidNumber: 2000
homeDirectory: /home/users/test/
</code></pre>
</div>
</li>
<li>
        <strong>Starts ldap server and add users.ldif</strong></p>
<div style="border:1px dotted #909090;background-color:#f7f7f7;overflow:auto;padding:4px;">
<pre>
<code>
sudo /etc/rc.d/sldap start
ldapadd -x -D "cn=admin,dc=company,dc=com" -f users.ldif -W
</code></pre>
</div>
</li>
<li><strong>Test ldap server</strong> searching for sample_user_1 user
<div style="border:1px dotted #909090;background-color:#f7f7f7;overflow:auto;padding:4px;">
<pre>
<code>
ldapsearch -x -D "cn=admin,dc=company,dc=com" -b "dc=company,dc=com" "(&#38;(uid=sample_user_1))" -W
</code></pre>
</div>
</li>
</ul>
<p></p>
<hr />
</p>
<ul>
<li><strong>And now scala code <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </strong>
<div style="border:1px dotted #909090;background-color:#f7f7f7;overflow:auto;padding:4px;">
<pre>
<code>
import java.io.FileInputStream
import java.util.{Hashtable, Properties}

import javax.naming.Context
import javax.naming.directory.{BasicAttributes, SearchControls}
import javax.naming.ldap.{LdapName, InitialLdapContext}

import scala.collection.jcl.{MapWrapper}
import scala.util.logging.{Logged, ConsoleLogger}

implicit def convert(javaMap: Hashtable[String, String]) = {
    Map.empty ++ new MapWrapper[String, String]() {
        def underlying = javaMap
    }
} 

type StringMap = Map[String, String]

val DEFAULT_URL = "localhost"
val DEFAULT_BASE_DN = ""
val DEFAULT_USER = ""
val DEFAULT_PASSWORD = ""

object SimpleLDAPSearch {
    lazy val ldap: LDAPSearch = {
        if (properties() == null) {
            val p = new Properties()
            p.load(new FileInputStream(propertiesFile()))

            // automatically calls convert(javaMap: Hashtable[String, String])
            properties = () =&#62; p.asInstanceOf[StringMap]
        }

        new LDAPSearch(properties()) with ConsoleLogger
    }

    var properties: () =&#62; StringMap = () =&#62; null
    var propertiesFile: () =&#62; String = {
        () =&#62; "DEFAULT_PROPERTIES_FILE.properties"
    }
}

class LDAPSearch(parameters: StringMap) extends Logged {
    lazy val initialContext = getInitialContext(parameters)

    def search(filter: String) : List[String] = {
        log("--&#62; LDAPSearch.search: Searching for '%s'".format(filter))

        var list = List[String]()

        val ctx = initialContext

        if (!ctx.isEmpty) {
            val result = ctx.get.search(parameters.getOrElse("ldap.base", DEFAULT_BASE_DN),
                                        filter,
                                        getSearchControls())

            while(result.hasMore()) {
                var r = result.next()
                list = list ::: List(r.getName)
            }
        }

        return list
    }

    def bindUser(dn: String, password: String) : Boolean = {
        log("--&#62; LDAPSearch.bindUser: Try to bind user '%s'".format(dn))

        var result = false

        try {
            var env = new Hashtable[String, String]()
            env.put(Context.PROVIDER_URL, parameters.getOrElse("ldap.url", DEFAULT_URL))
            env.put(Context.SECURITY_AUTHENTICATION, "simple")
            env.put(Context.SECURITY_PRINCIPAL, dn + "," + parameters.get("ldap.base"))
            env.put(Context.SECURITY_CREDENTIALS, password)
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory")

            var ctx = Some(new InitialLdapContext(env, null))

            result = !ctx.isEmpty
            ctx.get.close
        }
        catch {
            case e: Exception =&#62; println(e)
        }

        log("--&#62; LDAPSearch.bindUser: Bind successfull ? %s".format(result))

        return result
    }

    private def getInitialContext(props: StringMap) : Option[InitialLdapContext] = {

        log("--&#62; LDAPSearch.getInitialContext: Get initial context from '%s'".format(props.get("ldap.url")))

        var env = new Hashtable[String, String]()
        env.put(Context.PROVIDER_URL, props.getOrElse("ldap.url", DEFAULT_URL))
        env.put(Context.SECURITY_AUTHENTICATION, "simple")
        env.put(Context.SECURITY_PRINCIPAL, props.getOrElse("ldap.userName", DEFAULT_USER))
        env.put(Context.SECURITY_CREDENTIALS, props.getOrElse("ldap.password", DEFAULT_PASSWORD))
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory")

        return Some(new InitialLdapContext(env, null))
    }

    private def getSearchControls() : SearchControls = {
        val searchAttributes = new Array[String](1)
        searchAttributes(0) = "cn"

        val constraints = new SearchControls()
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE)
        constraints.setReturningAttributes(searchAttributes)
        return constraints
    }
}

// SimpleLDAPSearch.propertiesFile = () =&#62; "ldap.properties"

SimpleLDAPSearch.properties = () =&#62; {
    Map("ldap.url" -&#62; "ldap://localhost",
        "ldap.userName" -&#62; "cn=admin,dc=company,dc=com",
        "ldap.password" -&#62; "password",
        "ldap.base" -&#62; "dc=company,dc=com")
}

val list1 = SimpleLDAPSearch.ldap.search("(uid=sample_user_1)")
println(SimpleLDAPSearch.ldap.bindUser(list1(0), "password"))
</code></pre>
</div>
<p>The code is not exactly perfect,<br />
but shows how simple can scala be.
    </li>
</ul>
<h3>Here&#8217;s my favourites lines of code :</h3>
<ul>
<li>
        <strong>Automatically convert types</strong></p>
<div style="border:1px dotted #909090;background-color:#f7f7f7;overflow:auto;padding:4px;">
<pre><code>
implicit def convert(javaMap: Hashtable[String, String]) = {
    Map.empty ++ new MapWrapper[String, String]() {
        def underlying = javaMap
    }
}
</code></pre>
</div>
<p>To automatically convert a java.util.Hashtable (java.util.Properties) into a scala Map,<br />
Example :
<div style="border:1px dotted #909090;background-color:#f7f7f7;overflow:auto;padding:4px;">
<pre><code>
val hashtable: java.util.Hastable[String, String] = new java.util.Hashtable[String, String]()
hashtable.put("some_key", "some_value")

val map = hashtable.asInstanceOf[Map[String, String]]
</code></pre>
</div>
</li>
<li>
        <strong>A var that contains a method that returns the ldap properties file</strong></p>
<div style="border:1px dotted #909090;background-color:#f7f7f7;overflow:auto;padding:4px;">
<pre><code>
object SimpleLDAPSearch {
    var propertiesFile: () =&#62; String = {
        () =&#62; "DEFAULT_PROPERTIES_FILE.properties"
    }
..
// The SimpleLDAPSearch singleton propertiesFile method can be override in any moment
SimpleLDAPSearch.propertiesFile = () =&#62; "/tmp/ldap.properties"
</code></pre>
</div>
</li>
</ul>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Scala compile message - Class file or Jar is broken]]></title>
<link>http://mythinkpond.wordpress.com/2009/11/16/scala-compile-message-class-file-or-jar-is-broken/</link>
<pubDate>Mon, 16 Nov 2009 15:51:05 +0000</pubDate>
<dc:creator>Venkatt Guhesan</dc:creator>
<guid>http://mythinkpond.wordpress.com/2009/11/16/scala-compile-message-class-file-or-jar-is-broken/</guid>
<description><![CDATA[Sometimes when compiling my Scala code, the compiler output may need a little bit of help in sorting]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Sometimes when compiling my Scala code, the compiler output may need a little bit of help in sorting out what&#8217;s the real issue.</p>
<p>For example, when I compiled today I received the following error:</p>
<pre class="brush: jscript;">

[scalac] error: error while loading DefaultHttpClient, class file 'C:\A_OpenSource\WicketNotesApp\lib\httpclient-4.0.jar(org/apache/http/impl/client/DefaultHttpClient.class)' is broken
[scalac] (class net.jcip.annotations.ThreadSafe not found.)

[scalac] error: error while loading AbstractHttpClient, class file 'C:\A_OpenSource\WicketNotesApp\lib\httpclient-4.0.jar(org/apache/http/impl/client/AbstractHttpClient.class)' is broken
[scalac] (class net.jcip.annotations.ThreadSafe not found.)
</pre>
<p>And my instinct tells me to focus on the jar file or the class file and in this case, &#8220;DefaultHttpClient.class&#8221; or &#8220;AbstractHttpClient.class&#8221; or &#8220;httpclient-4.0.jar&#8221;. There&#8217;s noting wrong with your jar file or the Java class. The actual problem is in the next line, namely &#8220;class net.jcip.annotations.ThreadSafe not found.&#8221; It&#8217;s a class-not-found error.</p>
<p>So if you encounter a &#8220;broken&#8221; error when compiling Scala &#8211; the following line after the broken message can help you find the real error. It can save you a whole lot of head-aches and chasing the wrong tail.</p>
<blockquote><p>If you find this article useful, consider signing up for my RSS feed or Email Newsletter. See links on the right side.</p></blockquote>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[It's a great time to be a language buff]]></title>
<link>http://bytebaker.com/2009/11/16/its-a-great-time-to-be-a-language-buff/</link>
<pubDate>Mon, 16 Nov 2009 13:22:22 +0000</pubDate>
<dc:creator>Shrutarshi Basu</dc:creator>
<guid>http://bytebaker.com/2009/11/16/its-a-great-time-to-be-a-language-buff/</guid>
<description><![CDATA[I make no secret of the fact that I have a very strong interest in programming languages. So I was n]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I make no secret of the fact that I have a very strong interest in programming languages. So I was naturally very interested when news of the Go Programming Language hit the intertubes. Go is an interesting language. It pulls together some very powerful features with a familiar, but clean syntax and has lightning fast compile times. It certainly takes a place on my to-learn list along with Haskell and Scala. But even as Go becomes the latest hot piece of language news, it dawned on me that over the past few years we&#8217;ve seen a slew of interesting languages offering compelling alternatives to the industry &#8220;mainstream&#8221;.</p>
<p>I guess it all started with the rise of scripting languages like Python, PHP, Ruby and the poster boy of scripting: Perl. Personally, these languages with their dynamic typing, &#8220;batteries included&#8221; design and interesting syntax provided a breath of fresh air from the likes of C++ and Java. Not that C++ and Java are necessarily bad languages, but they aren&#8217;t the most interesting of modern languages. In the early years of this decade  computers were just getting fast enough to write large scale software in scripting languages. Things have changed a lot since then.</p>
<p>Dynamic languages aren&#8217;t just reserved for small scripts. Software like Ruby on Rails has proved that you can write really robust back end infrastructure with them. The languages for their part have kept on growing, adding features and making changes that keep them interesting and downright fun to use. Python 3.0 was a brave decision to make a break from backwards compatibility in order to do interesting things and it goes to show that these languages are far from ossifying or degrading.</p>
<p>Then there is JavaScript which was supposed to die a slow death by attrition as web programmers moved to Flash or Silverlight. But we all know that didn&#8217;t happen. JavaScript has stayed in the background since the rise of Netscape, but it&#8217;s only recently with advances in browser technology and growing standards support that it has really come into its own. I&#8217;ve only played with it a little, but it&#8217;s a fun little language which makes me feel a lot of the same emotions I felt when discovering Python for the first time. Thanks to efforts like Rhino, you can even use JavaScript on the client side for non-web related programming.</p>
<p>Of course, if you want to do really interesting things with these languages, then performance is not optional. Within the last year or two there&#8217;s been a strong push in both academia and industry to find ways to make these languages faster and safer. Google in particular seems to be in the thick of it. Chrome&#8217;s V8 JavaScript engine is probably the fastest client side JavaScript environment and their still experimental Unladen Swallow project has already made headway in improving Python performance. V8 has already enabled some amazing projects and I&#8217;m waiting to see what Unladen Swallow will do.</p>
<p>While we&#8217;re on the topic of performance, mentioning the Java Virtual Machine is  a must. The language itself seems to have fallen from grace lately, but the JVM is home to some of the most powerful compiler technology on the planet. It&#8217;s no wonder then that the JVM has become the target for a bunch of interesting languages. There are the ports of popular languages &#8212; JRuby,  Jython and Rhino. But the more interesting ones are the JVM-centric ones. Scala is really interesting in that it was born of an academic research project but is becoming the strongest contender to Java&#8217;s position of premier JVM language. Clojure is another language that I don&#8217;t think many people saw coming. It brings the power of LISP to a modern JVM unleashing a wide range of possibilities. It has it&#8217;s detractors, but it&#8217;s certainly done a fair bit to make Lisp a well known name again.</p>
<p>Academia has always been a hot bed when it comes to language design. It&#8217;s produced wonders like Lisp and Prolog and is making waves again with creations like Haskell (whose goal is ostensibly to avoid popularity at all costs) and the ML group of languages. These powerful functional languages with wonderful type inference are a language aficionado&#8217;s dream come true in many ways and they still have years of innovation ahead of them.</p>
<p>Almost as a corollary to the theoretically grounded functional languages, systems languages have been getting some love too. D and now Go are both languages that acknowledge that C and C++ have both had their heyday and it&#8217;s time to realize that systems programming does not have to be synonymous with bit twiddling. D has gotten some flak recently for not evolving very cleanly over the last few years, but something is better than nothing. Also a real shift towards eliminating manual memory management is a welcome addition.</p>
<p>As someone who intends to seriously study language design and the related concepts in the years to come, it&#8217;s a really great time to be in getting involved in learning about languages. At the moment I&#8217;m trying to teach myself Common Lisp and I have a Scala book sitting on the shelf too. One fo these days, I plan on sitting down and making a little toy language to get used to the idea of creating a language. Till then, it&#8217;s going to be really interesting just watching how things work out in an increasingly multilingual world.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Little tricks on working with LARGE list in Scala]]></title>
<link>http://ekkmanz.wordpress.com/2009/11/15/little-tricks-on-working-with-large-list-in-scala/</link>
<pubDate>Sat, 14 Nov 2009 18:27:09 +0000</pubDate>
<dc:creator>ekkman</dc:creator>
<guid>http://ekkmanz.wordpress.com/2009/11/15/little-tricks-on-working-with-large-list-in-scala/</guid>
<description><![CDATA[Since right now I&#8217;m processing large amount of binary files (300+ files * 4MB each) in Scala a]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Since right now I&#8217;m processing <strong>large </strong>amount of binary files (300+ files * 4MB each) in Scala and store some of results in a list. Some of typical method may not result good when processing in terms of large lists. So here is the tip I can share with you guys from my<strong> trial &#38; error</strong>:</p>
<h2>Beware RECURSIVE method!</h2>
<p>This is such an obvious evil that you may already known this. If you&#8217;re working with processing the list result and get <strong>stack overflow error </strong>then I suspect you&#8217;re somehow using <strong>recursive </strong>method. Avoid that if possible. One method I had discovered to lead to stack overflow is <strong>dropRight </strong>since I use this method in order to reduce list size. Others also had shown that <a href="http://oldfashionedsoftware.com/2009/07/10/scala-code-review-foldleft-and-foldright/">foldRight </a>could cause this error as well. If you want to know which method may harm you then you may tries using scala interpreter and construct List of integer that the size is larger then 4K elements. However if you REALLY want to know then I suggest you go for source code.</p>
<h2><strong>Immutable List</strong> should be use <strong>cautiously</strong>.</h2>
<p>Why? Because Immutable is not mutable! That means the list may not change over time, and the only way to add / remove element by using immutable list is to <strong>return a new list</strong>. If you&#8217;re trying to constantly append the processing result into a list by the end of each iteration, then you are going to reassign list every iteration. This could drain your memory real fast. My alternatives is that you may prefer <strong>scala.collection.mutable.ListBuffer</strong> instead.</p>
<h2>Watch out for linear-time method usage while processing lists</h2>
<p>Since processing multiple files may yield a list of result for each iteration, which each element had to be stored in another list (with same index). Writing codes like this within main file reading loop:</p>
<pre>for ( i &#60;- 0 until loopResult.length ) {
    //Some other process also going on
    processResult(i) += loopResult(i)
}
</pre>
<p>had cost me <strong>extra 60 seconds</strong> comparing with this loop when I&#8217;m processing files in byte-by-byte fashion, with each loop result had 20 elements. (Be advised that my actual logic is more complex than this but just to show the idea)</p>
<pre>for ( elem &#60;- loopResult.zipWithIndex ) {
    //Some other process also going on
    processResult(elem._2) += elem._1
}</pre>
<p>And it even could be optimized with using <strong>zip </strong>command like below. However I haven&#8217;t tried it myself so I cannot guarantee this is better.</p>
<pre>for ( elem &#60;- loopResult zip processResult ) {
    elem._2 += elem._1
}</pre>
<h2>Processing &#8220;result list&#8221; after file reading loop if possible.</h2>
<p>It&#8217;s reasonable to processing file to get result for each loop and append it into a result list. However if you may require extra processing e.g. sort the list or filter out N least element, then it&#8217;s better to process these after you&#8217;ve complete reading the file because processing these stuffs will usually lead you to <strong>O(n^2)</strong> when n = file size. You can even use <strong>immutable list</strong> and <strong>sort </strong>method for this case. For my case, I had to filter out the least element to reduce the size of the list from 300K to 40K. It took <strong>less than a few seconds</strong> when I process this after completely processing whole file, comparing to forever (It tooks so long and I kill its process) when I tries to achieve this within file reading loop.</p>
<p>&#160;</p>
<p>If you&#8217;re interested in processing large files, then don&#8217;t forget to read <a href="http://www.jayconrod.com/cgi/view_post.py?27">Processing large files with Scala</a> as well. His contribution really saves my ass since I totally have no idea on what to start at all.</p>
<p>However I do believe these might not fit everyone since you usually don&#8217;t have to work with large list. Some tips might also slow your coding speed down so please adjust this tips accordingly to your need.</p>
<p>That&#8217;s it for what I&#8217;ve discovered. You guys can share or even comments about this since I&#8217;m just a scala (and functional language) newbie.</p>
<p>&#160;</p>
<p><strong>Edit</strong>: Rewrite in easily-readable style.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Forwarding to a URL from Wicket]]></title>
<link>http://mythinkpond.wordpress.com/2009/11/13/forwarding-to-a-url-from-wicket/</link>
<pubDate>Fri, 13 Nov 2009 18:21:56 +0000</pubDate>
<dc:creator>Venkatt Guhesan</dc:creator>
<guid>http://mythinkpond.wordpress.com/2009/11/13/forwarding-to-a-url-from-wicket/</guid>
<description><![CDATA[Sometimes we need to forward to a servlet or resource that&#8217;s outside of Wicket such as a servl]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Sometimes we need to forward to a servlet or resource that&#8217;s outside of Wicket such as a servlet. Here&#8217;s how:</p>
<p>1. Modify your web.xml to define your servlet as well as your Wicket application &#8220;ignorePaths&#8221; init-param:</p>
<pre class="brush: xml;">
&#60;?xml version=&#34;1.0&#34; encoding=&#34;UTF-8&#34;?&#62;
&#60;!DOCTYPE web-app PUBLIC &#34;-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN&#34; &#34;http://java.sun.com/dtd/web-app_2_3.dtd&#34;&#62;
&#60;web-app&#62;
 &#60;display-name&#62;Wicket Example&#60;/display-name&#62;
 &#60;filter&#62;
 &#60;filter-name&#62;MyApplication&#60;/filter-name&#62;
 &#60;filter-class&#62;org.apache.wicket.protocol.http.WicketFilter&#60;/filter-class&#62;
 &#60;init-param&#62;
 &#60;param-name&#62;applicationClassName&#60;/param-name&#62;
 &#60;param-value&#62;com.gu.MyApplication&#60;/param-value&#62;
 &#60;/init-param&#62;
 &#60;init-param&#62;
 &#60;param-name&#62;wicket.configuration&#60;/param-name&#62;
 &#60;param-value&#62;deployment&#60;/param-value&#62;
 &#60;/init-param&#62;
 &#60;init-param&#62;
 &#60;param-name&#62;ignorePaths&#60;/param-name&#62;
 &#60;param-value&#62;images/,s/&#60;/param-value&#62;
 &#60;/init-param&#62;
 &#60;/filter&#62;
 &#60;filter-mapping&#62;
 &#60;filter-name&#62;MyApplication&#60;/filter-name&#62;
 &#60;url-pattern&#62;/*&#60;/url-pattern&#62;
 &#60;/filter-mapping&#62;
 &#60;servlet&#62;
 &#60;servlet-name&#62;SomeServlet&#60;/servlet-name&#62;
 &#60;servlet-class&#62;com.gu.SomeServlet&#60;/servlet-class&#62;
 &#60;/servlet&#62;
 &#60;servlet-mapping&#62;
 &#60;servlet-name&#62;SomeServlet&#60;/servlet-name&#62;
 &#60;url-pattern&#62;/s/koolkat.do&#60;/url-pattern&#62;
 &#60;/servlet-mapping&#62;
&#60;/web-app&#62;
</pre>
<p>The first observation is that Wicket is running as a Filter and not a Servlet. Second, the init-param &#8211; &#8220;ignorePaths&#8221; says that anything in the &#8220;/images&#8221; and &#8220;/s/*&#8221; will be ignored by Wicket Filter and passed along downstream.</p>
<p>2. Next in your Wicket Form, within your onSubmit method override you can do the following:</p>
<pre class="brush: java;">
class TestForm extends Form(id){
  @override
  public TestForm(String id, SomeFormModel ghfm)
  {
    //Code removed
  }
  @override
  public onSubmit()
  {
    String url = &#34;/s/koolkat.do&#34;; //some url within the same web-context
    getRequestCycle().setRequestTarget(new RedirectRequestTarget(url));
  }
}
</pre>
<p>Notice that the url field <strong>does not</strong> contain the &#8220;ContextPath&#8221;. Wicket takes care of that in the background. On the other hand, suppose you wanted to redirect to a URL ourside of your web context or to an external site then you would set the variable like this.</p>
<pre class="brush: java;">
String url = &#34;http://mythinkpond.wordpress.com/2009/11/13/forwarding-to-a-url-from-wicket/&#34;;  //or
url = &#34;http://myserver:port/othercontext/someurl&#34;;
</pre>
<p>On some rare occasions, you might want to get the servlet Request Dispatcher to forward a request. For that it gets a little tricky.</p>
<p>&#8211; In your  class you want to grab the &#8220;HttpServletResponse&#8221;. I&#8217;ve been unsuccessful in getting it in the  class.</p>
<pre class="brush: java;">
class xyz extends WebPage{
  public xyz()
  {
     HttpServletResponse response = getWebRequestCycle().getWebResponse().getHttpServletResponse();
     //additional code
     xyxForm thisForm = new xyzForm(thisModel, response);
  }
}

class xyzForm extends Form{
  HttpServletResponse response;

  public xyzForm(xyzModel model, HttpServletResponse thisResponse)
  {
     response = thisResponse;
  }

   public onSubmit() {
     HttpServletRequest request = getWebRequest().getHttpServletRequest();
     //additional code here
     getWebRequest().getHttpServletRequest().getRequestDispatcher(url).forward(request, response);
  }
}
</pre>
<blockquote><p>Please note that the above code is pseudo-code and not actual code because I was writing it in Scala and not Java. But for the audience, I&#8217;m trying to express it in Java so that it can have the greatest impact.</p></blockquote>
<p>That&#8217;s it! Happy Coding!</p>
<blockquote><p>If you find this article useful, consider signing up for my RSS feed or Email Newsletter. See links on the right side.</p></blockquote>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Filastrocca sulla superstizione - Limerick about superstition]]></title>
<link>http://nutrimente2.wordpress.com/2009/11/13/filastrocca-sulla-superstizione-limerick-about-superstition/</link>
<pubDate>Fri, 13 Nov 2009 06:26:17 +0000</pubDate>
<dc:creator>nutrimente2</dc:creator>
<guid>http://nutrimente2.wordpress.com/2009/11/13/filastrocca-sulla-superstizione-limerick-about-superstition/</guid>
<description><![CDATA[di Daniela Domenici Né di Venere né di Marte ci si sposa o si parte se poi il 13 e il 17 a questi gi]]></description>
<content:encoded><![CDATA[di Daniela Domenici Né di Venere né di Marte ci si sposa o si parte se poi il 13 e il 17 a questi gi]]></content:encoded>
</item>
<item>
<title><![CDATA[Scala Seminar Diversity: Topvrouwen aan het Woord ]]></title>
<link>http://lovecookie2008.wordpress.com/2009/11/12/scala-seminar-diversity-topvrouwen-aan-het-woord/</link>
<pubDate>Thu, 12 Nov 2009 11:28:20 +0000</pubDate>
<dc:creator>Orchid of Life</dc:creator>
<guid>http://lovecookie2008.wordpress.com/2009/11/12/scala-seminar-diversity-topvrouwen-aan-het-woord/</guid>
<description><![CDATA[Netwerkbijeenkomst: Scala ‘Allochtone Vrouwen aan de Top’ Datum: 10 november 2009 Waar: WTC Rotterda]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><img class="alignnone size-medium wp-image-1450" title="v.l.n.r: Famile Arslan, advocaat en procureur, Ingrid Pinas, gynaecoloog, Alsu Saitova, Luitenant bij de RNLAF, naam?" src="http://lovecookie2008.wordpress.com/files/2009/11/p1020105.jpg?w=300" alt="v.l.n.r: Famile Arslan, advocaat en procureur, Ingrid Pinas, gynaecoloog, Alsu Saitova, Luitenant bij de RNLAF, naam?" width="300" height="225" /></p>
<p><strong>Netwerkbijeenkomst: Scala ‘Allochtone Vrouwen aan de Top’ </strong></p>
<p>Datum: 10 november 2009<br />
Waar: WTC Rotterdam<br />
Hoeveel mensen: rond de 50<br />
Verhouding man/vrouw: 99% vrouw</p>
<p><strong>Vrouwen met Pit aan het woord </strong><br />
Er waren 4 spreeksters met een enorme kracht en drive om goed te zijn in wat zij doen. Ondanks de barrieres die zij in hun leven hebben gehad zijn zij door gegaan. Zij hebben kansen gezien en gegrepen, omdat zij een duidelijk doel voor ogen hadden en nog steeds hebben.</p>
<p><strong>Wie zijn deze vrouwen? </strong></p>
<p>1. Een 38-jarige vrouw van Turkse afkomst met de naam Famile Fatma Arslan heeft 5 jaar bij Ministerie van Justitie gewerkt. Zij is nu al 7 jaar ondernemer en kan zich een van de beste advocaten van Nederland noemen. Op 4-jarige leeftijd kwam zij met haar ouders naar Nederland. Het zou in eerste instantie voor 2 jaar zijn, maar ze zijn nu na 34 jaar niet meer teruggekeerd naar Turkije. Ze komt uit het oost-Turkije dat wordt gedomineerd door een mannencultuur. Toen zij 11 werd, kreeg zij van de basisschool het advies dat zij de huishoudschool moest gaan doen. Haar vader was hier op tegen. Hij had namelijk van zijn vader, die een welvarende veehouderij had in Turkije, niet de kans gekregen om te gaan studeren. Hij werd na een paar uur school door zijn vader van school gesleurd om alles te leren in het bedrijf, zodat hij het later over kon gaan nemen. Dit zorgde ervoor dat hij beter wilde voor zijn 1e dochter.</p>
<p>Na het schooladvies heeft zij 1 jaar lang thuis gezeten. Ze werd gek. Op jonge leeftijd zorgde zij voor haar moeder en haar twee broertjes. De huishoudschool was zeker overbodig. Zij deed al alles in huis. Ze vroeg aan haar vader om scholing en kreeg als antwoord. Als jij ervoor kan zorgen dat je wordt toegelaten tot de mavo, havo of vwo opleiding dan mag jij van mij naar school. Uiteindelijk kreeg zij op 12-jarige leeftijd een directeur zover die haar 2 maanden lang de tijd gaf om proef te draaien. Gedurende deze 2 maanden mocht ze geen enkele onvoldoende halen. Na de mavo heeft zij ook de havo en het atheneum doorlopen. Ze is rechten gaan studeren. Soliciteerde naar een baan op MBO niveau binnen Ministerie van Justitie. Ging vervolgens met de juiste mensen koffie drinken en kreeg hierdoor een baan die aansloot op haar studie Rechten.</p>
<p>2. Een 40-jarige Hindoestaans-Surinaamse vrouw die op haar 30ste een megadeal sloot als jurist voor een telecom bedrijf. Ongelooflijk. Ze verkocht het bedrijf voor 1.2 miljard euro aan Engelsen. Hierna kwam zij terecht in de directie bij hetzelfde of een ander bedrijf. Na 2 jaar stortte de telecom industrie in. Op haar 33ste ging zij trouwen met een manager die werkzaam was bij hetzelfde telecom bedrijf. Haar man ging voor zichzelf beginnen en zij bleef werken. Op haar 35ste kreeg zij haar eerste kind en op haar 39ste haar tweede kind. Haar verhaal inspireerde mij, omdat zij er nu ontzettend goed uitziet, getrouwd is, twee kinderen heeft en een ambitieuze echtgenoot. Zij blijven elkaar de ruimte geven om te groeien. Prachtig om te horen. Wat ik helemaal prachtig vond om te horen, was dat zij altijd de steun van haar ouders heeft gehad. Toen zij voor de beslissing stond om in een Telecom bedrijf te stappen die over 2 maanden verkocht moest worden, was haar vader degene die haar motiveerde om de stap te wagen. Het was nieuw voor haar, maar ze ging de uitdaging aan.</p>
<p>Ze is rechten gaan studeren, omdat zij vanuit huis uit een sterk rechtvaardigheidsgevoel had ontwikkeld. Haar vader is zeer begaan met de politiek en weet precies wat welke minister doet. Na haar rechtenstudie kreeg zij een baan als manager van grote projecten. Projecten waar miljarden euro’s in omgingen.</p>
<p>3. Een Rusissche vrouw van 25 jaar oud kwam ook aan het woord. Zij gaf heel duidelijk aan dat je elke kans die je ziet, ruikt of hoort moet aangrijpen. Iets wat je interesseert, doe het, geeft het aan, schreeuw het van de daken. Laat je horen. Dat is ook iets wat zij tijdens haar opleiding binnen Defensie heeft moeten leren. Spreken met luide stem zonder microfoon. Zij stond er! Waanzinnig gaaf. Een sterke vrouw die opgegroeid is tusen vrouwen. Tussen haar oma en moeder. Zij spreekt goed Nederlands, maar wel met een licht Russische accent. Haar vriend is net zo ambitieus. In de periode dat haar vriend voor 2 jaar naar Amerika ging voor een vliegopleiding is zij een Master gaan doen. Als vrouw moest zij zich binnen de mannencultuur van Defensie bewijzen. Op haar eerste werkdag kwam zij aanzetten met een enorme grote roze mok met een etiket en de leus: ‘the best man for the job is a woman’. De mok bestaat nog steeds</p>
<p>4. De vierde vrouw is over de 50 en van Surinaamse afkomst. Iemand die nu directeur is van de FeM-Kliniek in Zwolle. Zij had een mega inhoudelijke presentatie over hoe je het begrip ‘allochtone topvrouwen’ ook kunt zien. Haar boodschap is: je moet je niet in een hokje laten stoppen. Je moet gaan voor wat jij wil. Blijf jezelf ontwikkelen en elke tegenslag is een kans. Een kans om een andere weg in te stappen en je te ontwikkelen op deze weg. Geweldig!! Geen woorden voor.</p>
<p>Door Chungmei Cheng van <a href="http://www.orchidoflife.nl/" target="_blank">Orchid of Life -LifeCoaching </a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Introducing the DMPP Amiga debugger]]></title>
<link>http://codingnaked.wordpress.com/2009/11/11/introducing-the-dmpp-amiga-debugger/</link>
<pubDate>Wed, 11 Nov 2009 07:58:53 +0000</pubDate>
<dc:creator>Wei-ju Wu</dc:creator>
<guid>http://codingnaked.wordpress.com/2009/11/11/introducing-the-dmpp-amiga-debugger/</guid>
<description><![CDATA[I had this actually running for some time now: It is a graphical debugger which helps me understand ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I had this actually running for some time now: It is a graphical debugger which helps me understand how the 68000 instructions in the Kickstart ROM affect my Amiga emulator&#8217;s state. Here is a screen shot:</p>
<p style="text-align:center;"><img class="aligncenter size-full wp-image-210" title="DMPP Debugger" src="http://codingnaked.wordpress.com/files/2009/11/debugger_screenshot12.jpg" alt="DMPP Debugger" width="800" height="559" /></p>
<p>It is currently mainly a view to the Mahatma68k CPU, the two CIA-8520&#8217;s and the custom chip registers. It can execute a defined number of steps and any changes to the chip registers or CPU state will show there. I am currently implementing a function which displays a tooltip for each custom chip register to show a little more information than just its numerical value. The CIA&#8217;s and the CPU have only a few registers, so it is still feasible to display the role of each flag in the main view. The sheer amount of custom chip registers however, made it even hard to get them all in one frame.<br />
By the way, compliments to the developers of Scala Swing &#8211; these are very nice wrappers ! I started with conventional Java Swing components and then realized that Scala Swing makes programming user interfaces much easier. As a long time user,  Swing does really seem to be all that difficult to me, still I like it when the code looks as tidy as it does when using Scala Swing.</p>
<p>What else is new today ? I have made my second file release to Mahatma68k today. As its main addition, it now comes with the Javadocs the distribution archive and made sure only to have the methods and classes in there that matter to the user of the library.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[MongoDB and Scala]]></title>
<link>http://pronetics.wordpress.com/2009/11/10/mongodb-and-scala/</link>
<pubDate>Tue, 10 Nov 2009 08:11:31 +0000</pubDate>
<dc:creator>desmax74</dc:creator>
<guid>http://pronetics.wordpress.com/2009/11/10/mongodb-and-scala/</guid>
<description><![CDATA[Author:Massimiliano Dessì]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><!-- SlideShare error: doc is missing or has illegal characters /[^-_a-zA-Z0-9]/ --></p>
<p>Author:Massimiliano Dessì</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Open Source in Finance eXchange: December 15]]></title>
<link>http://skillsmatterblog.wordpress.com/2009/11/09/open-source-in-finance-exchange-december-15/</link>
<pubDate>Mon, 09 Nov 2009 17:07:56 +0000</pubDate>
<dc:creator>Skills Matter</dc:creator>
<guid>http://skillsmatterblog.wordpress.com/2009/11/09/open-source-in-finance-exchange-december-15/</guid>
<description><![CDATA[Places are going fast for this year&#8217;s Open Source in Finance eXchange on December 15.  Speakin]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p style="text-align:center;"><a href="http://skillsmatter.com/event/design-architecture/open-source-in-finance-exchange/js-432"><img class="aligncenter size-full wp-image-19" title="open-source-in-finance-456x100" src="http://skillsmatterblog.wordpress.com/files/2009/11/open-source-in-finance-456x1001.gif" alt="open-source-in-finance-456x100" width="450" height="98" /></a></p>
<p>Places are going fast for this year&#8217;s Open Source in Finance eXchange on December 15.  Speaking across six expert talks and two parkbench discussions on the day will be Alan  Hardy, Rob Davies, Angelo Corsaro and David Vincent.</p>
<p>This year&#8217;s eXchange is bringing together the leading experts in Open Source technology and Financial Services software development with innovators, technologists, architects and developers in the developer community.</p>
<p>The day promises to combine deep technical insight with friendly discussion around creating highly scalable, secure systems and leveraging OS technology within the finance sector.</p>
<p>The programme is structured to encourage discussion and bring together the leading thinkers and experts on the use open source technology in Financial Services with passionate members of the developer community in this sector.</p>
<p>To keep it as informal as possible we are strictly limiting the event to 125 delegates, and it is already proving to be popular.  What&#8217;s more, on the day we will be raffling off a ticket to this year&#8217;s QCon in London.</p>
<p><strong>Book now &#8212; and get your tickets for </strong><strong><strong>£65.  Just click the banner at the top of the page.</strong><br />
</strong></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Simply Scala]]></title>
<link>http://unstableterrain.wordpress.com/2009/11/09/simply-scala/</link>
<pubDate>Mon, 09 Nov 2009 07:36:27 +0000</pubDate>
<dc:creator>Trent</dc:creator>
<guid>http://unstableterrain.wordpress.com/2009/11/09/simply-scala/</guid>
<description><![CDATA[In the same manner as Try Ruby comes Simply Scala &#8211; a neat way to check out the programming la]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>In the same manner as <a href="http://tryruby.sophrinix.com/">Try Ruby</a> comes <a href="http://www.simplyscala.com/">Simply Scala</a> &#8211; a neat way to check out the programming language in a hassle-free way. Work through the tutorial or pursue undirected learning &#8211; there&#8217;s a full Scala <a href="http://en.wikipedia.org/wiki/Read-eval-print_loop">REPL</a> available to use.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Scala Mashup Series: The Template Method in Java, Spring and Scala]]></title>
<link>http://ice09.wordpress.com/2009/11/09/scala-mashup-series-the-template-method-in-java-spring-and-scala/</link>
<pubDate>Mon, 09 Nov 2009 02:03:23 +0000</pubDate>
<dc:creator>ice09</dc:creator>
<guid>http://ice09.wordpress.com/2009/11/09/scala-mashup-series-the-template-method-in-java-spring-and-scala/</guid>
<description><![CDATA[Continuing the Scala Mashup Series, this post is about a quite important, often used, but also contr]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Continuing the Scala Mashup Series, this post is about a quite important, often used, but also controversial pattern: The Template Method.</p>
<p>In general, there are great explanations of the pattern <a href='http://en.wikipedia.org/wiki/Template_method_pattern'>in Wikipedia</a> and of course in <a href='http://www.amazon.com/gp/product/0596007124?ie=UTF8&#38;tag=ice09-20&#38;link_code=as3&#38;camp=211189&#38;creative=373489&#38;creativeASIN=0596007124'>Head First Design Patterns</a>.</p>
<p><b>Criticism</b></p>
<p>A very good summary of the Template Method pattern especially in comparison to the Strategy pattern is on <a href='http://stackoverflow.com/questions/669271/what-is-the-difference-between-the-template-and-the-strategy-pattern'>stackoverflow.com</a>:</p>
<p>The Template pattern does <b>compile-time algorithm selection by subclassing</b>.<br />
The Strategy pattern does <b>run-time algorithm selection by containment</b>.</p>
<p><b>Example</b></p>
<p>Imagine you want to arrange a dinner. The entire algorithm for arranging a dinner is predefined: </p>
<ol>
<li>Invite your guests</li>
<li>Go shopping</li>
<li>Clean your fridge to provide enough space</li>
<li>Prepare the meal</li>
<li>Server the meal</li>
<li>Wash the dishes</li>
</ol>
<p>Now, some parts of this algorithm (which in its entirety is called <i>arrange</i>) are fixed (invariant parts). Other parts are highly dependant on the meal you want to prepare (variant parts).<br />
In Template Method, the algorithm itself is described in a public accessible method, eg. <i>arrange()</i>, which combines and calls the variant and invariant methods. The invariant methods are implemented in the abstract super class. The variant parts are implemented in the concrete classes, eg. <i>BratwurstDinner</i>, which implements the concrete way to do shopping for the BratwurstDinner, as well as the preparation of the Bratwurst itself.<br />
The important part is the compile-time binding &#8211; the implementing, concrete classes cannot change their implementation during runtime.<br />
This makes the Template Method almost ideal for framework creation, when you want to provide abstract algorithms with certain concrete implementations (think of abstract database layers, with an algorithm which cares for opening &#38; establishing connections, handles exceptions and cleans up nicely after doing &#8230; the variant part, which is implemented in the concrete classes).</p>
<p>Here is the dinner example using the Template Method pattern<br />
<img src="http://ice09.wordpress.com/files/2009/11/dinnertm2.png"></img></p>
<p>Here is the dinner example using the Strategy pattern<br />
<img src="http://ice09.wordpress.com/files/2009/11/dinnerstrategy1.png"></img></p>
<p>There are two clever blog posts, one about <a href='http://tech.puredanger.com/2007/07/03/pattern-hate-template/'>disadvantages</a> of the Template Method pattern, and <a href='http://debasishg.blogspot.com/2009/01/subsuming-template-method-pattern.html'>one</a> mentioning a possible alternative in languages with <a href='http://en.wikipedia.org/wiki/First-class_function'>first class functions</a> like Scala.</p>
<p><b>Language comparison: Java, Scala, Spring</b></p>
<p>We will happily leave out the Java example, since it is just too obvious. In the Wikipedia article a sample is given, together with the class diagram it should be pretty obvious how Template Method is implemented in Java. The only thing to keep in mind is to set the super class <i>abstract</i>, as well as the variant methods &#8211; which are then implemented (using <i>@Override</i>) in the concrete classes.</p>
<p><i>Scala</i></p>
<p>In Scala there are is the intuitive way of implemeting the Template Method, analogous to Java:</p>
<pre class="brush: java;">
abstract class DinnerEvent {

  def arrange: Unit = {
    makeGuestList
    doShopping
    cleanFridge
    prepareMeal
    serveMeal
    washDishes
  }

  def prepareMeal: Unit
  def doShopping: Unit

  def makeGuestList: Unit = {
    println(&#34;making guest list...&#34;)
  }

  def cleanFridge: Unit = {
    println(&#34;cleaning fridge...&#34;)
  }

  def serveMeal: Unit = {
    println(&#34;serving meal...&#34;)
  }

  def washDishes: Unit = {
    println(&#34;washing dishes...&#34;)
  }

}

trait TurkeyDinner {

  def doShopping: Unit =  {
    println(&#34;...buying turkey&#34;)
  }

  def prepareMeal: Unit =  {
    println(&#34;...preparing turkey&#34;)
  }

}

object TemplateMethod {

  def main(args:Array[String]) = {
    val dinner = new DinnerEvent with TurkeyDinner
    dinner.arrange
  }

}
</pre>
<p>However, in languages with first class functions, it is too tempting to use the Strategy pattern:</p>
<pre class="brush: java;">
class DinnerEventWithStrategy(shoppingStrategy: =&#62; Unit, preparingStrategy: =&#62; Unit) {

  def arrange: Unit = {
    makeGuestList
    shoppingStrategy
    cleanFridge
    preparingStrategy
    serveMeal
    washDishes
  }

  def makeGuestList: Unit = {
    println(&#34;making guest list...&#34;)
  }

  def cleanFridge: Unit = {
    println(&#34;cleaning fridge...&#34;)
  }

  def serveMeal: Unit = {
    println(&#34;serving meal...&#34;)
  }

  def washDishes: Unit = {
    println(&#34;washing dishes...&#34;)
  }

}

object Closure {

  def turkeyShoppingStrategy: Unit = {
    println (&#34;...shopping turkey strategy&#34;)
  }

  def turkeyPreparationStrategy:Unit = {
    println (&#34;...preparing turkey strategy&#34;)
  }

  def main(args:Array[String]) = {
    val dinner = new DinnerEventWithStrategy(turkeyShoppingStrategy, turkeyPreparationStrategy)
    dinner.arrange
  }

}
</pre>
<p>So, you should choose wisely, both patterns definitely have their scope of application &#8211; just keep in mind that Strategy also uses composition over inheritance, which is always a good advise.</p>
<p><i>&#8230;and what about Spring?</i></p>
<p>This is interesting, Spring uses the Template Method a lot &#8211; and many think it is one of their greatest strengths.<br />
But wait &#8230; the Template Method pattern? Not really. The Spring Framework templates in fact are not implementing the Template Method pattern, even if it feels this way.<br />
Let&#8217;s examine a small usage example of Spring&#8217;s <a href='http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/ch12s02.html#jdbc-SimpleJdbcTemplate'>JdbcTemplate</a>:</p>
<pre class="brush: java;">
package com.commons.sample.dao;

import java.util.List;

import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

public class JdbcSimpleDao extends SimpleJdbcDaoSupport implements SimpleDao {

	final static String single	= &#34;select id, name from test where id = ?&#34;;
	final static String list 	= &#34;select id, name from test&#34;; 

	public Simple getSimpleById(int id) {
		return getSimpleJdbcTemplate().queryForObject(single,
				ParameterizedBeanPropertyRowMapper.newInstance(Simple.class), id);
	}

	public List&#60;Simple&#62; getSimples() {
		return getSimpleJdbcTemplate().query(list,
				ParameterizedBeanPropertyRowMapper.newInstance(Simple.class));
	}

}
</pre>
<p>What is happening here? Even though the class extends <i>SimpleJdbcDaoSupport</i>, it would not have to.<br />
The Method <i>query(&#8230;)</i> takes the SQL and a <i>ParameterizedBeanPropertyRowMapper.newInstance(Simple.class)</i>, which defines a row mapper that creates an object of class <i>Simple</i> &#8211; this certainly describes a strategy. So, even the so-called Spring Templates actually uses the Strategy pattern.</p>
<p><b>Summary</b></p>
<p>The Template Method is a powerful pattern. Use it if you create a framework, since you can inject certain functionality in the implementing classes at compile time, which let the user of your framework extend it easily, but in a controlled and &#8220;traceable&#8221; way. For Java, it is a natural way to enable users of your classes to extends the functionality at certain points.<br />
In languages with first-order functions (or closures), like Scala, it might feel more natural to use the Strategy pattern instead. However, keep in mind that the patterns are not completely identical.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Scala 備忘]]></title>
<link>http://scova0731.wordpress.com/2009/11/08/scala-%e5%82%99%e5%bf%98/</link>
<pubDate>Sun, 08 Nov 2009 10:51:01 +0000</pubDate>
<dc:creator>scova0731</dc:creator>
<guid>http://scova0731.wordpress.com/2009/11/08/scala-%e5%82%99%e5%bf%98/</guid>
<description><![CDATA[備忘です。 ()Unit … Javaのvoidに相当 Javaっぽくて括弧は必須: NG: if i &lt; 10 OK: if ( i &lt; 10 ) valは再代入不可、varは再代入可 ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>備忘です。</p>
<ul>
<li>()Unit … Javaのvoidに相当</li>
<li>Javaっぽくて括弧は必須:<br />
NG: if i &#60; 10<br />
OK: if ( i &#60; 10 )</li>
<li>valは再代入不可、varは再代入可</li>
<li>「=&#62;」と「&#60;-」</li>
<li>「:::」と「::」。なお、末尾がコロンの場合は、右被演算子</li>
<li>「Nil」は空リスト</li>
<li>タプル。異なる型をもてる。taple._1, taple._2, … 1から始まる。</li>
</ul>
<p>まだ、traitにはたどり着きません。。。先は長そう。</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Scalaの命令型的と関数型的]]></title>
<link>http://scova0731.wordpress.com/2009/11/08/scala%e3%81%ae%e5%91%bd%e4%bb%a4%e5%9e%8b%e7%9a%84%e3%81%a8%e9%96%a2%e6%95%b0%e5%9e%8b%e7%9a%84/</link>
<pubDate>Sun, 08 Nov 2009 10:24:28 +0000</pubDate>
<dc:creator>scova0731</dc:creator>
<guid>http://scova0731.wordpress.com/2009/11/08/scala%e3%81%ae%e5%91%bd%e4%bb%a4%e5%9e%8b%e7%9a%84%e3%81%a8%e9%96%a2%e6%95%b0%e5%9e%8b%e7%9a%84/</guid>
<description><![CDATA[次は同じものを表しています。 // &#8212; imperative style 命令型スタイル &#8212; var i = 0 while (i &lt; args.length ) { p]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>次は同じものを表しています。</p>
<blockquote><p>// &#8212; imperative style 命令型スタイル &#8212;<br />
var i = 0<br />
while (i &#60; args.length ) {<br />
println( args(i) )<br />
i += 1<br />
}</p>
<p>// &#8212; functional style 関数型スタイル &#8212;<br />
args.foreach(( arg: String ) =&#62; plintln(arg))</p></blockquote>
<p>関数型に慣れていくには、varを使わずvalだけ使っていくこと、とありました。</p>
<blockquote></blockquote>
</div>]]></content:encoded>
</item>

</channel>
</rss>
