<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Giordano Scalzo&#039;s Personal Blog &#187; tutorial</title>
	<atom:link href="http://giordano.scalzo.biz/category/tutorial/feed/" rel="self" type="application/rss+xml" />
	<link>http://giordano.scalzo.biz</link>
	<description>Just another useless weblog</description>
	<lastBuildDate>Mon, 09 May 2011 09:50:40 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.3</generator>
		<item>
		<title>Learn a bit of Ruby every day: block local variable</title>
		<link>http://giordano.scalzo.biz/2011/01/05/learn-a-bit-of-ruby-every-day-block-local-variable/</link>
		<comments>http://giordano.scalzo.biz/2011/01/05/learn-a-bit-of-ruby-every-day-block-local-variable/#comments</comments>
		<pubDate>Wed, 05 Jan 2011 16:52:19 +0000</pubDate>
		<dc:creator>giordano scalzo</dc:creator>
				<category><![CDATA[ruby]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://giordano.scalzo.biz/?p=330</guid>
		<description><![CDATA[In Ruby 1.8.7 it wasn&#8217;t possible define a local variable to a block, so the following code produces an exception: class Shape def initialize(args) @sides = args[:sides] end def draw puts "Drawing #{@sides} sides" end end square = Shape.new(sides: 4) sum = 0 (1..3).each do &#124;value&#124; square = value * value sum += square end [...]]]></description>
			<content:encoded><![CDATA[<p>In Ruby 1.8.7 it wasn&#8217;t possible define a local variable to a block, so the following code produces an exception:</p>
<pre class='brush: ruby'>
class Shape
  def initialize(args)
    @sides = args[:sides]
  end
  def draw
    puts "Drawing #{@sides} sides"
  end
end

square = Shape.new(sides: 4)
sum = 0
(1..3).each do |value|
  square = value * value
  sum	+= square
end
puts sum
square.draw
</pre>
<p>Ruby 1.9.2 it&#8217;s possible add a local variable to a block:</p>
<pre class='brush: ruby'>
class Shape
  def initialize(args)
    @sides = args[:sides]
  end
  def draw
    puts "Drawing #{@sides} sides"
  end
end

square = Shape.new(sides: 4)
sum = 0
(1..3).each do |value; square|
  square = value * value
  sum	+= square
end
puts sum
square.draw
</pre>
<p>Now it works as expected</p>

<!-- start wp-tags-to-technorati 1.02 -->

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://giordano.scalzo.biz/2011/01/05/learn-a-bit-of-ruby-every-day-block-local-variable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Learn a bit of Ruby every day: Dir.exist?</title>
		<link>http://giordano.scalzo.biz/2011/01/02/learn-a-bit-af-ruby-every-day-dir-exist/</link>
		<comments>http://giordano.scalzo.biz/2011/01/02/learn-a-bit-af-ruby-every-day-dir-exist/#comments</comments>
		<pubDate>Sun, 02 Jan 2011 21:38:36 +0000</pubDate>
		<dc:creator>giordano scalzo</dc:creator>
				<category><![CDATA[ruby]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://giordano.scalzo.biz/?p=323</guid>
		<description><![CDATA[Introduced in 1.9, it&#8217;s a cool method to know if a directory exists: Dir.exist?("/tmp") # => true Dir.exist?("/temp") # => false A more correct alias is Dir.exist?.]]></description>
			<content:encoded><![CDATA[<p>Introduced in 1.9, it&#8217;s a cool method to know if a directory exists:<br />
<code><br />
Dir.exist?("/tmp")                    # =>	true<br />
Dir.exist?("/temp")                  # =>	false<br />
</code><br />
A more correct alias is <code>Dir.exist?</code>.</p>

<!-- start wp-tags-to-technorati 1.02 -->

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://giordano.scalzo.biz/2011/01/02/learn-a-bit-af-ruby-every-day-dir-exist/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Objective-C for busy Java Developers 1: Calling methods</title>
		<link>http://giordano.scalzo.biz/2010/01/19/objective-c-for-busy-java-developers-1-calling-methods/</link>
		<comments>http://giordano.scalzo.biz/2010/01/19/objective-c-for-busy-java-developers-1-calling-methods/#comments</comments>
		<pubDate>Tue, 19 Jan 2010 13:34:43 +0000</pubDate>
		<dc:creator>giordano scalzo</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://giordano.scalzo.biz/?p=261</guid>
		<description><![CDATA[At last I got a wonderful MacBookPro, so I started to study Objective-C to develop some cool Iphone applications. Objective-C is a language derived from C, to which it adds some modern features as ObjectOriented or Smalltalk-style messaging. As far I&#8217;m a complete newbie, I&#8217;m trying to learn it recalling some well know patterns and [...]]]></description>
			<content:encoded><![CDATA[<p>At last I got a wonderful MacBookPro, so I started to study <a href="http://en.wikipedia.org/wiki/Objective-C">Objective-C</a> to develop some cool Iphone applications.</p>
<p><a href="http://en.wikipedia.org/wiki/Objective-C">Objective-C</a> is a language derived from C, to which it adds some modern features as ObjectOriented or Smalltalk-style messaging.</p>
<p>As far I&#8217;m a complete newbie, I&#8217;m trying to learn it recalling some well know patterns and scenarios as made in Java , following <a href="http://cocoadevcentral.com/d/learn_objectivec/">this good tutorial</a>.</p>
<p><a href="http://en.wikipedia.org/wiki/Objective-C">Objective-C</a> has a little strange way to call method, that could be disorienting at first glance:</p>
<p><b>Java</b>:</p>
<pre class='brush:java'>
object.method;
object.methodWithInput(input);

output = object.methodWithOutput();
output = object.methodWithInputAndOutput(Object input);
</pre>
<p><b>Objective-C</b>:</p>
<pre class='brush:c'>
[object method];
[object methodWithInput:input];

output = [object methodWithOutput];
output = [object methodWithInputAndOutput:input];
</pre>
<p>Obviously, it&#8217;s possible to call methods of class, instead of instance:</p>
<p><b>Java</b>:</p>
<pre class='brush:java'>
Object oString = new String();
</pre>
<p><b>Objective-C</b>:</p>
<pre class='brush:c'>
id oString = [NSString string];
</pre>
<p>The
<pre>id</pre>
<p> refers any kind of object, so it&#8217;s little different from Java counterpart.<br />
Better code is:</p>
<p><b>Java</b>:</p>
<pre class='brush:java'>
String sString = new String();
</pre>
<p><b>Objective-C</b>:</p>
<pre class='brush:c'>
NSString* sString = [NSString string];
</pre>
<p>With this style, it&#8217;s a little cumbersome write nested calls:</p>
<p><b>Java</b>:</p>
<pre class='brush:java'>
calculator.add(numbers.split());
</pre>
<p><b>Objective-C</b>:</p>
<pre class='brush:c'>
[calculator add:[numbers split]];
</pre>
<p>This syntax disencourage the nesting of more than one method.</p>
<p>Some methods take multiple input arguments, Objective-C deals with that allowing split method names:</p>
<p><b>Java</b>:</p>
<pre class='brush:java'>
boolean writeToFile(String path, boolean useAuxiliaryFile)

boolean result = myData.writeToFile("/tmp/log.txt", false);
</pre>
<p><b>Objective-C</b>:</p>
<pre class='brush:c'>
-(BOOL)writeToFile:(NSString *)path withAuxFile:(BOOL)useAuxiliaryFile;

BOOL result = [myData writeToFile:@"/tmp/log.txt" withAuxFile:NO];
</pre>
<p>Objective-C has properties built in, in Java you need to implement getters and setters:</p>
<p><b>Java</b>:</p>
<pre class='brush:java'>
photo.setCaption("Day at the Beach");
output = photo.getCaption();
</pre>
<p><b>Objective-C</b>:</p>
<pre class='brush:c'>
photo.caption = @"Day at the Beach";
output = photo.caption;
</pre>
<p>A property should be marked
<pre>@property</pre>
<p> in declaration and
<pre>@synthesize</pre>
<p> in implementation.</p>
<p>To create an object, the function
<pre>alloc</pre>
<p> should be called and then an init method should be called:</p>
<p><b>Java</b>:</p>
<pre class='brush:java'>
object = new ComplexObject(1.0f);
</pre>
<p><b>Objective-C</b>:</p>
<pre class='brush:c'>
object = [[ComplexObject alloc] initWithFloat:1.0f];
</pre>
<p>When working in an environment without garbage collector, any object created with alloc should be released:</p>
<p><b>Objective-C</b>:</p>
<pre class='brush:c'>
[object release];
</pre>
<p>To complete this introductory post, take a look at this <a href='http://giordano.scalzo.biz/wp-content/uploads/2010/01/objectiveccheatsheet.pdf'>ObjectiveC CheatSheet</a>: it contains all the most used constructs needed to start to code for Mac.</p>

<!-- start wp-tags-to-technorati 1.02 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/java' rel='tag' target='_self'>java</a>, <a class='technorati-link' href='http://technorati.com/tag/objective-c' rel='tag' target='_self'>objective-c</a>, <a class='technorati-link' href='http://technorati.com/tag/tutorial' rel='tag' target='_self'>tutorial</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://giordano.scalzo.biz/2010/01/19/objective-c-for-busy-java-developers-1-calling-methods/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>No more excuses 2: junit testing System time</title>
		<link>http://giordano.scalzo.biz/2009/11/07/no-more-excuses-2-junit-testing-system-time/</link>
		<comments>http://giordano.scalzo.biz/2009/11/07/no-more-excuses-2-junit-testing-system-time/#comments</comments>
		<pubDate>Sat, 07 Nov 2009 13:59:37 +0000</pubDate>
		<dc:creator>giordano scalzo</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[test]]></category>
		<category><![CDATA[trick]]></category>

		<guid isPermaLink="false">http://giordano.scalzo.biz/?p=197</guid>
		<description><![CDATA[Another common exemple of static dependency, it&#8217;s the Time System dependency. In greenfield project it could be possible inject time into the objects they&#8217;ll use it, but in legacy code it&#8217;s more difficult, so oftet we gave up and don&#8217;t unit test some behaviour dependent from time. In a recent project, I had the problem [...]]]></description>
			<content:encoded><![CDATA[<p>Another common exemple of static dependency, it&#8217;s the Time System dependency.<br />
In greenfield project it could be possible inject time into the objects they&#8217;ll use it, but in legacy code it&#8217;s more difficult, so oftet we gave up and don&#8217;t unit test some behaviour dependent from time.</p>
<p>In a recent project, I had the problem to check the correct format of a filename that it had to contain the creation timestamp; I easily overcame it with a nice test pattern made by <a href="http://c2.com/cgi/wiki?PaoloPerrotta">Paolo &#8220;Nusco&#8221; Perrotta</a>, well known <a href="http://pragprog.com/titles/ppmetr/metaprogramming-ruby">Ruby Metaprogramming guru</a>, in a version wrote by <a href="http://bbossola.wordpress.com/">Bruno Bossola</a> in a nice <a href="http://www.vqwiki.org/">Open Source project</a>.</p>
<p>In a nutshell, the trick is to <em>adapt </em>System Time with another object.</p>
<p>Let see a simple example.<br />
This is the class to test:</p>
<pre class="brush: java">
package biz.scalzo.prod;

import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeFormatter {
	public String now() {
		SimpleDateFormat sdf = new SimpleDateFormat(
				"yyyy/MM/dd HH:mm");
		return sdf.format(new Date(System.currentTimeMillis()));
	}
}
</pre>
<p>I know it mixes two responsibilities, it has a silly static dependecy and so on, but forgive my oversemplification used to show the pattern.</p>
<pre class="brush: java">
package biz.scalzo.test;

import junit.framework.Assert;
import org.junit.Test;

public class ATimeFormatter {
	@Test
	public void shouldFormatNowInFancyWay() {
		Assert.assertEquals("2009/10/13 15:29", new TimeFormatter().now());
	}

}
</pre>
<p>The behaviour to check is how well the Formatter formats current time in string; we have to find a way to set a well know time point so we can check te result of format.</p>
<p>To implement the <a href="http://c2.com/cgi/wiki?VirtualClock">VirtualClock</a> pattern, we declare a simple <em>Clock </em>interface:</p>
<pre class="brush: java">
package biz.scalzo.prod;

public interface Clock {
	public long now();
}
</pre>
<p>and a repository where we can insert our fake clock</p>
<pre class="brush: java">
package biz.scalzo.prod;

import java.util.Date;

public class SystemTime {
	private static Clock clock;

	private static final Clock defaultClock = new Clock() {
		public long now() {
			return System.currentTimeMillis();
		}
	};

	public static long asMillis() {
		return getClock().now();
	}

	public static Date asDate() {
		return new Date(getClock().now());
	}

	public static void reset() {
		clock = null;
	}

	public static void setClock(Clock aClock) {
		clock = aClock;
	}

	static Clock getClock() {
		return (clock != null ? clock : defaultClock);
	}
}
</pre>
<p>Now we can change our class using <em>SystemTime </em>instead of <em>System.currentTimeMillis(</em>):</p>
<pre class="brush: java">
package biz.scalzo.prod;

import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeFormatter {
	public String now() {
		SimpleDateFormat sdf = new SimpleDateFormat(
				"yyyy/MM/dd HH:mm");
		return sdf.format(SystemTime.asDate());
	}
}
</pre>
<p>In test harness we can inject a fake clock</p>
<pre class="brush: java">
package biz.scalzo.test;

import junit.framework.Assert;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import biz.scalzo.prod.Clock;
import biz.scalzo.prod.SystemTime;
import biz.scalzo.prod.TimeFormatter;

public class ATimeFormatter {
	private static final long FAKED_TIME = 1255440571354L;

	private void fakeClock() {
		SystemTime.setClock(new Clock() {
			public long now() {
				return FAKED_TIME;
			}
		});
	}

	@Before
	public void setUp(){
		fakeClock();
	}

	@Test
	public void shouldFormatNowInFancyWay() {
		Assert.assertEquals("2009/10/13 15:29", new TimeFormatter().now());
	}

}
</pre>
<p>and we have green bar! Neat, isn&#8217;t it?</p>
<p>I know it&#8217;s a lot of code, but in legacy code it&#8217;s better than leave a feature without a test.</p>

<!-- start wp-tags-to-technorati 1.02 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/java' rel='tag' target='_self'>java</a>, <a class='technorati-link' href='http://technorati.com/tag/test' rel='tag' target='_self'>test</a>, <a class='technorati-link' href='http://technorati.com/tag/trick' rel='tag' target='_self'>trick</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://giordano.scalzo.biz/2009/11/07/no-more-excuses-2-junit-testing-system-time/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Birthday Greetings Kata in Ruby</title>
		<link>http://giordano.scalzo.biz/2009/10/26/birthday-greetings-kata-in-ruby/</link>
		<comments>http://giordano.scalzo.biz/2009/10/26/birthday-greetings-kata-in-ruby/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 20:30:31 +0000</pubDate>
		<dc:creator>giordano scalzo</dc:creator>
				<category><![CDATA[agile]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[kata]]></category>

		<guid isPermaLink="false">http://giordano.scalzo.biz/?p=208</guid>
		<description><![CDATA[Lately the pratice of Kata seems spreading out very quickly, thanks to work of well known Software Craftsmen as Corey Haynes or the Clean Code evangelist Uncle Bob. It all started waiting for a kid&#8217;s karate lesson, and now it&#8217;s a well know practice to become a better developer. Basicly a code kata is a [...]]]></description>
			<content:encoded><![CDATA[<p>Lately the pratice of Kata seems spreading out very quickly, thanks to work of well known Software Craftsmen as <a href="http://www.coreyhaines.com">Corey Haynes</a> or the Clean Code evangelist <a href="http://blog.objectmentor.com/articles/category/uncle-bobs-blatherings">Uncle Bob</a>.</p>
<p><a href="http://codekata.pragprog.com/codekata/2007/01/code_katahow_it.html">It all started</a> waiting for a kid&#8217;s karate lesson, and now it&#8217;s a well know practice to become a better developer.</p>
<p>Basicly a code kata is a small problem to be resolved without any pressure and requests, but to play with different techniques or programming language.</p>
<p>Another interesting point of view considers a code kata as a training for muscles of memory, focusing on repetitions, memorizations of decisions and keyboard shortcuts; the point is: if I get trained to do design decisions at subconscious level, when I&#8217;ll met similar problems I&#8217;ll be very productive, doing the right decision without any logical think.<br />
Amazing, isn&#8217;t it?</p>
<p>The main argument of last <a href="http://milano-xpug.pbworks.com/">Milan Xpug meeting</a> was the <a href="http://matteo.vaccari.name/blog/archives/154">Birthday Greetings Kata</a>, a workshop Matteo Vaccari will submit to next <a href="http://www.xpday.net/Xpday2009/sessions/Birthday%20Greetings%20Kata.html">Xp Days Benelux 2009</a>.<br />
Unfortunately I couldn&#8217;t be present, but I <a href="http://github.com/gscalzo/Birthday-Greetings-Kata/tree/in_ruby">implemented the kata</a> on my own, using Ruby instead of Java.</p>
<p>I enjoyed it very much, and I start thinking to try it still a couple of times and then screencasting it: I&#8217;m far behind <a href="http://katas.softwarecraftsmanship.org/">this level</a>, but review my actions can help me get better.</p>
<pre class="brush: ruby">
$:.unshift File.join(File.dirname(__FILE__), *%w[.. lib])
require 'rumbster'
require 'message_observers'
require 'net/smtp'
require 'gserver'
require 'birthday_service'
require 'employee_repository'

describe "Greetings Service" do
	NON_STANDARD_PORT = 10015
	def send_message(to, message)
    		Net::SMTP.start('localhost', NON_STANDARD_PORT) do |smtp|
      			smtp.send_message message, 'your@mail.address', to
    		end
	end
	before :each do
	 	@rumbster =  Rumbster.new(NON_STANDARD_PORT)
   		@message_observer = MailMessageObserver.new
		@rumbster.add_observer @message_observer
		@rumbster.start

		@birthdayService = BirthdayService.new("localhost", NON_STANDARD_PORT);
	end
	after :each do
		@rumbster.stop
	end
	context "with a file with one person born today" do
		before :each do
			@birthdayService.send_greetings EmployeeRepository.new("employee_data.txt"), "2008/10/08"
		end

		it "should send one email" do
			@message_observer.messages.size.should == 1
		end

		it "should send correct message" do
			@message_observer.messages.first.subject.should == "Happy Birthday!"
			@message_observer.messages.first.body.chomp.should == "Happy Birthday, dear John!"
			@message_observer.messages.first.to.should == ["john.doe@foobar.com"]
		end
	end

end
</pre>
<pre class="brush: ruby">
$:.unshift File.join(File.dirname(__FILE__), *%w[.. lib])
require "employee_repository"

describe "EmployeeRepository" do
	it "should read Employees from a file" do
		repository = EmployeeRepository.new "employee_data.txt"
	end

	it "should have a well know size" do
		repository = EmployeeRepository.new "employee_data.txt"
		repository.size.should == 3
	end
	it "should return first employee" do
		repository = EmployeeRepository.new "employee_data.txt"
		expected_employee = Employee.new("Doe, John, 1982/10/08, john.doe@foobar.com")
		repository.first.should == expected_employee
	end
	it "should return employees born an a given date" do
		repository = EmployeeRepository.new "employee_data.txt"
		expected_employee = Employee.new("Doe, John, 1982/10/08, john.doe@foobar.com")
		repository.born_on('2008/10/08').first.should == expected_employee
	end
end
</pre>
<pre class="brush: ruby">
$:.unshift File.join(File.dirname(__FILE__), *%w[.. lib])
require "message"
require "employee"

describe "Message" do
	before :each do
		@message = Message.new Employee.new("Doe, John, 1982/10/08, john.doe@foobar.com")
	end

	it "should have employee's email as destination" do
		@message.to.should == "john.doe@foobar.com"
	end
	it "should construct a complete body" do
		@message.body.should == "To: john.doe@foobar.com\nSubject: Happy Birthday!\n\nHappy Birthday, dear John!"
	end
end
</pre>
<pre class="brush: ruby">
require "message"

class BirthdayService
	def initialize(host, port)
		@host = host
		@port = port
	end
	def send_greetings(employees, date)
		employees.born_on(date).each do |employee|
			send_message(Message.new employee)
		end
	end
	def send_message(message)
    		Net::SMTP.start(@host, @port) do |smtp|
      			smtp.send_message message.body, 'your@mail.address', message.to
    		end
	end
end
</pre>
<pre class="brush: ruby">
class Employee
	attr_reader :firstname
	attr_reader :lastname
	attr_reader :birthdate
	attr_reader :email
	def initialize(args)
		tokens = args.split(',').map { |e| e.strip }
		@firstname = tokens[1]
		@lastname = tokens[0]
		@birthdate = tokens[2]
		@email = tokens[3]
	end

	def ==(other)
		other.instance_of?(self.class) &#038;&#038;
			@firstname == other.firstname &#038;&#038;
			@lastname == other.lastname &#038;&#038;
			@birthdate == other.birthdate &#038;&#038;
			@email == other.email
	end
end
</pre>
<pre class="brush: ruby">
require 'employee'

class String
	def same_day?(other)
		date1 = split('/')
		date2 = other.split('/')
		date1[1] == date2[1] &#038;&#038; date1[2] == date2[2]
	end
end

class EmployeeRepository
	private
	def skip_header
		@employees.shift
	end

	public
	def initialize(employees_filename)
		@employees = []
		File.open(employees_filename).each_line do |line|
			@employees << Employee.new(line)
		end
		skip_header
	end

	def size
		@employees.size
	end

	def first
		@employees.first
	end

	def born_on(current_date)
		@employees.find_all { |e| e.birthdate.same_day?(current_date) }
	end
end
</pre>
<pre class="brush: ruby">
class Message
	def initialize(employee)
		@employee = employee
	end
	def to
		@employee.email
	end
	def body
		["To: #{to}",
		"Subject: Happy Birthday!",
		"",
		"Happy Birthday, dear #{@employee.firstname}!"].join("\n")
	end
end
</pre>
<p>Interesting I wrote more specs code than production code.</p>
<p>I do like I didn't used any <em>IF</em>, but I don't like to open String to model date and the use of split to tokenize things: I'll focus on thant in next attempt!</p>

<!-- start wp-tags-to-technorati 1.02 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/kata' rel='tag' target='_self'>kata</a>, <a class='technorati-link' href='http://technorati.com/tag/ruby' rel='tag' target='_self'>ruby</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://giordano.scalzo.biz/2009/10/26/birthday-greetings-kata-in-ruby/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>No more excuses: junit testing log messages</title>
		<link>http://giordano.scalzo.biz/2009/10/21/no-more-excuses-junit-testing-log-messages/</link>
		<comments>http://giordano.scalzo.biz/2009/10/21/no-more-excuses-junit-testing-log-messages/#comments</comments>
		<pubDate>Wed, 21 Oct 2009 17:46:52 +0000</pubDate>
		<dc:creator>giordano scalzo</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[log4j]]></category>
		<category><![CDATA[tdd]]></category>

		<guid isPermaLink="false">http://giordano.scalzo.biz/?p=192</guid>
		<description><![CDATA[Althought I&#8217;m a straight adept of Tdd, sometime I can&#8217;t resist the temptation to write some production code without a test, above all if I have to implement some cross cutting behaviours, as could be logging . In project I worked on lately, a request was to manage some bad situations logging something at error [...]]]></description>
			<content:encoded><![CDATA[<p>Althought I&#8217;m a straight adept of Tdd, sometime I can&#8217;t resist the temptation to write some production code without a test, above all if I have to implement some cross cutting behaviours, as could be logging .</p>
<p>In project I worked on lately, a request was to manage some bad situations logging something at error level and go process next item; the temptation to implement it and check running the program was very appeliling, but my green wrist band and RailsConf 09 keynote by Uncle Bob I watched recentely, helped me resist.<br />
So I started searching, tried somenthing, and, finally, I came up with a neat solution.</p>
<p>Given this simple object</p>
<pre class='brush: java'>
package biz.scalzo.prod;

import org.apache.log4j.Logger;

public class LoggingObject {
	private static Logger log = Logger.getLogger(LoggingObject.class);

	public void starts() {
		log.info("I'm starting");
	}
}
</pre>
<p>we want to test if it writes log.<br />
To achieve this, we can use a simple custom appender, that records all messages in a list:</p>
<pre class='brush: java'>
package biz.scalzo.test;

import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LoggingEvent;

public class RecordingAppender extends AppenderSkeleton {
	private static List&lt;String> messages = new ArrayList&lt;String>();
	private static RecordingAppender appender = new RecordingAppender();

	private RecordingAppender() {
		super();
	}

	public static RecordingAppender appender(PatternLayout patternLayout) {
		appender.setLayout(patternLayout);
		appender.clear();
		return appender;
	}

	protected void append(LoggingEvent event) {
		messages.add(layout.format(event));
	}

	public void close() {
	}

	public boolean requiresLayout() {
		return true;
	}

	public static String[] messages() {
		return (String[]) messages.toArray(new String[messages.size()]);
	}

	private void clear() {
		messages.clear();
	}
}
</pre>
<p>With that, writing our test is a piece of cake:</p>
<pre class='brush: java'>
package biz.scalzo.test;

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;

import biz.scalzo.prod.LoggingObject;

public class ALoggingObject {

	private LoggingObject loggingObj;

	@Before
	public void setUp() {
		loggingObj = new LoggingObject();
		configureLog();
	}

	private boolean logContains(String expected) {
		String actual[] = RecordingAppender.messages();
		for (String log : actual) {
			if (log.contains(expected))
				return true;
		}
		return false;
	}

	private void configureLog() {
		Logger rootLogger = Logger.getRootLogger();
		rootLogger.removeAllAppenders();
		rootLogger.setLevel(Level.INFO);
		rootLogger.addAppender(new ConsoleAppender(new PatternLayout(
				"%d [%t] %-5p %c{1} - %m%n")));
		rootLogger.addAppender(RecordingAppender.appender(new PatternLayout(
				"%-5p - %m%n")));
	}

	@Test
	public void shouldLogWhenStarts() {
		loggingObj.starts();
		assertTrue(logContains("I'm starting"));
	}

}
</pre>
<p>Neat, simple and clear: no more excuses to not test logging!</p>

<!-- start wp-tags-to-technorati 1.02 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/junit' rel='tag' target='_self'>junit</a>, <a class='technorati-link' href='http://technorati.com/tag/log4j' rel='tag' target='_self'>log4j</a>, <a class='technorati-link' href='http://technorati.com/tag/tdd' rel='tag' target='_self'>tdd</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://giordano.scalzo.biz/2009/10/21/no-more-excuses-junit-testing-log-messages/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Installing Sinatra on Site5</title>
		<link>http://giordano.scalzo.biz/2009/09/24/installing-sinatra-on-site5/</link>
		<comments>http://giordano.scalzo.biz/2009/09/24/installing-sinatra-on-site5/#comments</comments>
		<pubDate>Thu, 24 Sep 2009 09:28:05 +0000</pubDate>
		<dc:creator>giordano scalzo</dc:creator>
				<category><![CDATA[ruby]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[sinatra]]></category>
		<category><![CDATA[site5]]></category>

		<guid isPermaLink="false">http://giordano.scalzo.biz/?p=127</guid>
		<description><![CDATA[I think Rails is a wonderful framework that boosts the success of Ruby, but sometimes is a a little overkill. Enter Sinatra, a microframework in Ruby, aims to create simple web applications. As mentioned in a previous post, I own a shared access on a Site5, so I began to search any documentation to install [...]]]></description>
			<content:encoded><![CDATA[<p>I think Rails is a wonderful framework that boosts the success of Ruby, but sometimes is a a little overkill.<br />
Enter <a href="http://www.sinatrarb.com/">Sinatra</a>, a microframework in Ruby, aims to  create simple web applications.</p>
<p>As mentioned in a previous post, I own a shared access on a Site5, so I began to search any documentation to install a simple Sinatra  app on Site5.<br />
I didn&#8217;t find a lot of documentation, but a <a href="http://ostblog.sroegner.org/?p=99">post</a> gave some hints in the right direction.</p>
<p>First of all, it need to install locally Sinatra gem configuring <code>GEM_PATH</code> and <code>GEM_HOME</code>.<br />
Then we need to create a subdomain, i.e. <code>sinatra.scalzo.biz</code>, where we&#8217;ll implement Sinatra&#8217;s app. For an unknown reason, I&#8217;d to configure a subdirectory as document root:</p>
<p><img src="http://giordano.scalzo.biz/wp-content/uploads/2009/09/domain_config.png" alt="Domain Configuration" title="Domain Configuration" width="519" height="191" class="aligncenter size-full wp-image-133" /></p>
<p>The htaccess directory contains the file <code>.htaccess</code> that enables <a href="http://www.modrails.com/">Phusion Passenger</a>:</p>
<pre class='brush: bash'>
PassengerEnabled on
RackBaseURI /
</pre>
<p>In parent directory we write the <a href="http://www.modrails.com/">Phusion Passenger</a> configuration,  <code>config.ru</code>:</p>
<pre class='brush: ruby'>
ENV['GEM_PATH'] = "/home/USER/gems:/usr/lib/ruby/gems/1.8"
ENV['GEM_HOME'] = "/home/USER/gems"
require 'rubygems'
require 'sinatra'

require 'app'
run Sinatra.application
</pre>
<p>and  our Sinatra application (I call it <code>app</code>):</p>
<pre class='brush: ruby'>
get '/' do
  "Hello World!"
end
get '/hi' do
  "Hi World!"
end
</pre>
<p>That&#8217;s it!<br />
Now we can call the urls &#8216;<code>http://sinatra.scalzo.biz/</code>&#8216; and &#8216;<code>http://sinatra.scalzo.biz/hi</code>&#8216;.</p>

<!-- start wp-tags-to-technorati 1.02 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/ruby' rel='tag' target='_self'>ruby</a>, <a class='technorati-link' href='http://technorati.com/tag/sinatra' rel='tag' target='_self'>sinatra</a>, <a class='technorati-link' href='http://technorati.com/tag/site5' rel='tag' target='_self'>site5</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://giordano.scalzo.biz/2009/09/24/installing-sinatra-on-site5/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Using JDave: A quick introduction to specs framework</title>
		<link>http://giordano.scalzo.biz/2009/09/17/using-jdave-a-quick-introduction-to-specs-framework/</link>
		<comments>http://giordano.scalzo.biz/2009/09/17/using-jdave-a-quick-introduction-to-specs-framework/#comments</comments>
		<pubDate>Thu, 17 Sep 2009 15:13:47 +0000</pubDate>
		<dc:creator>giordano scalzo</dc:creator>
				<category><![CDATA[bdd]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[jdave]]></category>

		<guid isPermaLink="false">http://giordano.scalzo.biz/?p=90</guid>
		<description><![CDATA[As second Bdd engine to try, I choose JDave, a specification oriented engine. JBehave is, instead, user-stories-oriented: the difference is very subtle and I&#8217;m not sure I caught it completely . Anyway, JDaveis inspired by RSpec, at the moment the most used bdd engine, so I thought it deserved a try. In order to compare [...]]]></description>
			<content:encoded><![CDATA[<p>As second Bdd engine to try, I choose <a href="http://www.jdave.org/">JDave</a>, a specification oriented engine.<br />
<a href="http://jbehave.org/">JBehave </a>is, instead, user-stories-oriented: the difference is very subtle and I&#8217;m not sure I caught it completely <img src='http://giordano.scalzo.biz/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> .<br />
Anyway, <a href="http://www.jdave.org/">JDave</a>is inspired by <a href="http://rspec.info/">RSpec</a>, at the moment the most used bdd engine, so I thought it deserved a try.<br />
In order to compare <a href="http://www.jdave.org/">JDave</a> with <a href="http://jbehave.org/">JBehave</a>, I implemented the StringTemplater kata, as in my <a href="http://giordano.scalzo.biz/2009/09/04/bdd-with-jbehave/">previous post</a>.</p>
<h3>Installing JDave</h3>
<p>After creating a java project, I simply downloaded the <a href="http://www.jdave.org/resources.html">last version of JDave</a> and extracted all jar in lib directory of my project:</p>
<p><img src="http://giordano.scalzo.biz/wp-content/uploads/2009/09/bdd.png" alt="JDave Jars" title="JDave Jars" width="259" height="441" class="aligncenter size-full wp-image-97" /></p>
<p>They are a lot of jars, and I&#8217;m sure I won&#8217;t use all of them, but it&#8217;s just a try so it doesn&#8217;t deserve the time to filter only the used ones.</p>
<p><a href="http://jbehave.org/">JBehave</a> is a story runner, so each scenario must be written as:</p>
<pre><strong>Given</strong> something
<strong>When </strong>something happens
<strong>Then </strong>this happens</pre>
<p>Instead, <a href="http://www.jdave.org/">JDave</a> is a specification engine and each scenario show a behavior of a class:</p>
<pre>AThingIWantToWrite
  - ShouldDoThis
  - ShouldDoThat
  - ShouldntDoThat</pre>
<p>In other words, <a href="http://jbehave.org/">JBehave</a> is similar to <a href="http://cukes.info/">Cucumber</a>, <a href="http://www.jdave.org/">JDave</a> is similar to <a href="http://rspec.info/">RSpec</a>.</p>
<p>Writing a specification is really straightforward:<br />
first of all, we create a <code>Specification </code>object, passing the object we want to write; then we create a serie of inner classes:</p>
<pre class="brush: java">@RunWith(JDaveRunner.class)
public class StringTemplaterSpec extends Specification&lt;ThingIWantToWrite&gt; {
	public class AThingIWantToWrite {
		public void ShouldDoThis() {
		}
		public void ShouldDoThat() {
		}
        }
   ...
}</pre>
<p>As <a href="http://jbehave.org/">JBehave</a>, <a href="http://www.jdave.org/">JDave</a> is a wrapper built over JUnit, so we can use our Ide integration to run the specifications.<br />
That&#8217;s it!</p>
<h3>The code</h3>
<p>As in <a href="http://giordano.scalzo.biz/2009/09/04/bdd-with-jbehave/">JBehave try</a>, I implemented the same scenarios as in Corey Haines Video:</p>
<pre class="brush: java">package biz.scalzo.kata.stringtemplater.jdave;

import org.junit.runner.RunWith;

import jdave.Specification;
import jdave.junit4.JDaveRunner;

@RunWith(JDaveRunner.class)
public class StringTemplaterSpec extends Specification&lt;StringTemplater&gt; {
	public class AStringTemplater {
		private StringTemplater stringTemplater;

		public void create() {
			stringTemplater = new StringTemplater();
		}

		public void shouldReturnEmptyWhenAnEmptyStringIsPassed() {
			specify(stringTemplater.replace(""), must.equal(""));
		}

		public void shouldReturnTheOriginalStringWhenNoMarkersArePassed() {
			specify(stringTemplater.replace("original string"), must.equal("original string"));
		}

		public void shouldReplaceAToken() {
			specify(stringTemplater.replace("Hello, $name","name: giordano"),
					must.equal("Hello, giordano"));
		}

		public void shouldReplaceTwoTokens() {
			specify(stringTemplater.replace("Hello, $name, how a $attitude day","name: giordano, attitude:  wonderful"),
					must.equal("Hello, giordano, how a wonderful day"));
		}

		public void shouldRemoveNotProvidedMarkers() {
			specify(stringTemplater.replace("Hello, $name, how a $attitude day","name: giordano"),
					must.equal("Hello, giordano, how a  day"));
		}
	}

}</pre>
<p>The Junit view of Eclipse is very explicative of the behaviors of StringTemplater:<br />
<img src="http://giordano.scalzo.biz/wp-content/uploads/2009/09/junit_view.png" alt="JUnit View" title="JUnit View" width="491" height="326" class="aligncenter size-full wp-image-98" /></p>
<p>For sake of completeness, this is the final implementation of StringTemplater:</p>
<pre class="brush: java">package biz.scalzo.kata.stringtemplater.jdave;

import java.util.Arrays;
import java.util.Iterator;

public class StringTemplater {

	public String replace(String stringToReplace) {
		return replace(stringToReplace, "");
	}

	public String replace(String stringToReplace, String markers) {
		return replace(stringToReplace, initialIterator(markers));
	}

	private String[] tupla(String pair) {
		return pair.split(":");
	}

	private Iterator&lt;String&gt; initialIterator(String markers) {
		return Arrays.asList(markers.split(",")).iterator();
	}

	private String replace(String stringToReplace, Iterator&lt;String&gt; markers) {
		if (!markers.hasNext())
			return stringToReplace;
		String[] pair = tupla(markers.next());
		String newString = stringToReplace.replace(name(pair), value(pair));
		return replaceEmptyMarkers(replace(newString, markers));
	}

	private String replaceEmptyMarkers(String replace) {
		return replace.replaceAll("\\$\\w+", "");
	}

	private String value(String[] pair) {
		return (pair.length != 2) ? "" : pair[1].trim();
	}

	private String name(String[] pair) {
		if (pair.length != 2)
			return "";
		return "$" + pair[0].trim();
	}
}</pre>
<h3>Conclusions</h3>
<p><a href="http://www.jdave.org/">JDave</a> is very easy to learn and the specifications written throught it are very complete and expressive.<br />
If I have to make a choice, I liked slightly more <a href="http://www.jdave.org/">JDave</a>, but I think are just two tools: BDD is a way to think, not a framework or an engine to use.</p>
<p>In conclusions, I believe <a href="http://jbehave.org/">JBehave </a>and <a href="http://www.jdave.org/">JDave</a> could be used together, the former to describe the user stories, at user level, the latter to describe the behaviors of the classes, at developer level.</p>

<!-- start wp-tags-to-technorati 1.02 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/bdd' rel='tag' target='_self'>bdd</a>, <a class='technorati-link' href='http://technorati.com/tag/eclipse' rel='tag' target='_self'>eclipse</a>, <a class='technorati-link' href='http://technorati.com/tag/java' rel='tag' target='_self'>java</a>, <a class='technorati-link' href='http://technorati.com/tag/jdave' rel='tag' target='_self'>jdave</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://giordano.scalzo.biz/2009/09/17/using-jdave-a-quick-introduction-to-specs-framework/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Bdd with JBehave</title>
		<link>http://giordano.scalzo.biz/2009/09/04/bdd-with-jbehave/</link>
		<comments>http://giordano.scalzo.biz/2009/09/04/bdd-with-jbehave/#comments</comments>
		<pubDate>Fri, 04 Sep 2009 11:50:20 +0000</pubDate>
		<dc:creator>giordano scalzo</dc:creator>
				<category><![CDATA[bdd]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[jbehave]]></category>
		<category><![CDATA[kata]]></category>

		<guid isPermaLink="false">http://www.scalzo.biz/?p=32</guid>
		<description><![CDATA[Somebody defined Behaviour-Driven Development &#8220;TDD done right&#8221;; maybe is a bit too provocative as definition, but I think it&#8217;s the time to get my hands wet and give Bdd a chance. JBehave is the first BDD&#8217;s framework, developed by the BDD&#8217;s inventor himself, Dan North, and still one of the more supported in Java community. [...]]]></description>
			<content:encoded><![CDATA[<p>Somebody defined <a href="http://behaviour-driven.org/" target="_blank">Behaviour-Driven Development</a> &#8220;TDD done right&#8221;; maybe is a bit too provocative as definition, but I think it&#8217;s the time to get my hands wet and give Bdd a chance.</p>
<p><a href="http://jbehave.org/" target="_blank">JBehave</a> is the first BDD&#8217;s framework, developed by the BDD&#8217;s inventor himself, <a href="http://dannorth.net/" target="_blank">Dan North</a>, and still one of the more supported in Java community.</p>
<p>I choose a simple kata to develop in Bdd-way, the StringTemplater kata, as saw in a <a href="http://www.coreyhaines.com/" target="_blank">Corey Haines</a>&#8216; <a href="http://blog.envylabs.com/2009/08/corey-haines-performance-kata/" target="_blank">video</a> and following this excellent <a href="http://www.shaafshah.com/2009/08/12/getting-started-with-jbehave-in-8-steps/" target="_blank">post</a>.</p>
<h3>JBehave on Eclipse: half an hour tutorial</h3>
<p>First of all, we should create a project under Eclipse and add JBehave <a href="http://jbehave.org/software/download/" target="_blank">jars</a>.</p>
<p>Then we should write the basic infrastructure: a textual file with the scenarios and two classes connecting our stories to JBehave.</p>
<p>By default the scenarios file should be without extension and in the same directory of classes, but, aiming to separate specs code and production code, I created a new source directory called <code>scenario</code>.</p>
<p>The scenarios file should have a meaningful name and the words should separated by underscores; in this example I called it <code>replace_tokens_in_string</code>.</p>
<p>At the beginning of the file, we can write the story we should implement: it isn&#8217;t mandatory, but it&#8217;s useful if we use specs to comunicate with the customers.<br />
Following we can write a first basic scenario:</p>
<pre class="brush: bash">Story: replace tokens in String
As a user
I would like replace token in a string with values
So that I can create templates for my configuration files

Scenario: replace empty string
Given I have a StringTemplater
When I ask to replace an emptystring
Then I should get an emptystring</pre>
<p>The story is just descriptive, but the scenario must be of the form of<br />
<code><strong>Given</strong> something<br />
<strong>When</strong> action<br />
<strong>Then</strong> check</code></p>
<p>Now we need create two java classes.<br />
The first one is JBehave wrapper to JUnit TestCase and its name should match the one of textual file converted in CamelCase: in our example should be <code>ReplaceTokensInString</code>.</p>
<pre class="brush: java">package biz.scalzo.kata.stringtemplater.jbehave;

import org.jbehave.scenario.Scenario;

public class ReplaceTokensInString extends Scenario{
	  public ReplaceTokensInString() {
	        super(new ReplaceTokensInStringSteps());
	    }
}</pre>
<p>The second class, <code>ReplaceTokensInStringSteps</code>, implementing the steps of the scenario:</p>
<pre class="brush: java">package biz.scalzo.kata.stringtemplater.jbehave;

import org.jbehave.scenario.steps.Steps;

public class ReplaceTokensInStringSteps extends Steps {
}</pre>
<p>That&#8217;s it!<br />
As said before, JBehave is built over JUnit so we can run <code>ReplaceTokensInString</code> as Junit test obtaining a message from the engine:</p>
<pre class="brush: bash">Story: replace tokens in String
As a user
I would like replace token in a string with values
So that I can create templates for my configuration files

Scenario: replace empty string

Given I have a StringTemplater (PENDING)
When I ask to replace an emptystring (PENDING)
Then I should get an emptystring (PENDING)</pre>
<p><code>PENDING</code> means we have to build that step; so we do it with an empty implementation:</p>
<pre class="brush: java">package biz.scalzo.kata.stringtemplater.jbehave;

import org.jbehave.scenario.annotations.Given;
import org.jbehave.scenario.annotations.Then;
import org.jbehave.scenario.annotations.When;
import org.jbehave.scenario.steps.Steps;

public class ReplaceTokensInStringSteps extends Steps {
	@Given("I have a StringTemplater")
	public void createStringTemplater() {
	}
	@When("I ask to replace an emptystring")
	public void replaceAnEmptystring() {
	}
	@Then("I should get an emptystring")
	public void shouldGetEmptyString() {
	}
}</pre>
<p>and when we run again the test, the <code>PENDING</code> messages should disappear.</p>
<p>This is the basic infrastructure, but, in my tiny experience was the most difficult part: once the empty scenario worked, implement the complete kata was quite straightforward.</p>
<p>This is my final scenarios file:</p>
<pre class="brush: java">Story: replace tokens in String
As a user
I would like replace token in a string with values
So that I can create templates for my configuration files

Scenario: replace empty string
Given I have a StringTemplater
When I ask to replace an emptystring
Then I should get an emptystring

Scenario: replace string without tokens
Given I have a StringTemplater
When I ask to replace 'this string'
Then I should get 'this string'

Scenario: replace string with a token
Given I have a StringTemplater
When I ask to replace 'Hello, $name' with [name : pippo]
Then I should get 'Hello, pippo'

Scenario: replace string with two tokens
Given I have a StringTemplater
When I ask to replace 'Hello, $name, how a $attitude day' with [name : pippo, attitude: wonderful]
Then I should get 'Hello, pippo, how a wonderful day'

Scenario: replace string with two adjacent tokens
Given I have a StringTemplater
When I ask to replace 'Hello, $adj$name' with [name : friend, adj: good]
Then I should get 'Hello, goodfriend'

Scenario: replace string with two tokens and only one value
Given I have a StringTemplater
When I ask to replace 'Hello, $name, how a $attitude day' with [name : pippo]
Then I should get 'Hello, pippo, how a  day'</pre>
<p>This my steps:</p>
<pre class="brush: java">package biz.scalzo.kata.stringtemplater.jbehave;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.jbehave.Ensure.ensureThat;

import org.jbehave.scenario.annotations.Given;
import org.jbehave.scenario.annotations.Then;
import org.jbehave.scenario.annotations.When;
import org.jbehave.scenario.steps.Steps;

public class ReplaceTokensInStringSteps extends Steps {
	private StringTemplater templater;
	private String result;

	@Given("I have a StringTemplater")
	public void createStringTemplater() {
		templater = new StringTemplater();
	}

	@When("I ask to replace an emptystring")
	public void replaceAnEmptystring() {
		result = templater.replace("");
	}

	@Then("I should get an emptystring")
	public void shouldGetEmptyString() {
		ensureThat(result, is(equalTo("")));
	}

	@When("I ask to replace '$stringToReplace'")
	public void replaceStringWithoutTokens(String stringToReplace) {
		result = templater.replace(stringToReplace);
	}

	@Then("I should get '$expected'")
	public void checkStringResult(String expected) {
		ensureThat(result, is(equalTo(expected)));
	}

	@When("I ask to replace '$stringToReplace' with [$tokens]")
	public void replaceStringWithTokens(String stringToReplace, String tokens) {
		result = templater. replace(stringToReplace,tokens);
	}

}</pre>
<p>and, last but not least, <code>StringTemplater</code> class:</p>
<pre class="brush: java">package biz.scalzo.kata.stringtemplater.jbehave;

import java.util.HashMap;
import java.util.Map.Entry;

public class StringTemplater {

	public String replace(String originaleString) {
		return replace(originaleString, "");
	}

	public String replace(String stringToReplace, String tokensAsString) {
		HashMap tokensMap = splitTokens(tokensAsString);
		return removeKeywordWithoutValue(replaceKeywords(stringToReplace,
				tokensMap));
	}

	private String removeKeywordWithoutValue(String replaceKeywords) {
		return replaceKeywords.replaceAll("\\$\\w+", "");
	}

	private String replaceKeywords(String initialValue,
			HashMap tokensMap) {
		String result = initialValue;
		for (Entry entry : tokensMap.entrySet()) {
			result = result
					.replaceAll("\\$" + entry.getKey(), entry.getValue());
		}
		return result;
	}

	private HashMap splitTokens(String tokensAsString) {
		String[] pairs = splitPairs(tokensAsString);

		HashMap result = new HashMap();
		for (String pair : pairs) {
			String[] tokens = pair.split(":");
			if (tokens.length &gt; 1) {
				result.put(tokens[0].trim(), tokens[1].trim());
			}
		}
		return result;
	}

	private String[] splitPairs(String tokensAsString) {
		return tokensAsString.split(",");
	}
}</pre>
<h3>Conclusions</h3>
<p>This is my first impact with Bdd in Java, I liked and I think it&#8217;s very promising.<br />
Neverthless, I still don&#8217;t know if it is something I can do in day by day work or just a proof of concept: Jbehave is quite verbose and the stories are high level specifications, so we need to write a lot of boilerplate code to specify a class.</p>
<p>In my trip in Bdd-land, next steps will be give other Bdd engines a try, starting with ones written in high level languages as <a href="http://www.easyb.org/" target="_blank">easyb</a> or <a href="http://www.artima.com/scalatest/" target="_blank">scalatest</a>.</p>

<!-- start wp-tags-to-technorati 1.02 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/bdd' rel='tag' target='_self'>bdd</a>, <a class='technorati-link' href='http://technorati.com/tag/eclipse' rel='tag' target='_self'>eclipse</a>, <a class='technorati-link' href='http://technorati.com/tag/java' rel='tag' target='_self'>java</a>, <a class='technorati-link' href='http://technorati.com/tag/jbehave' rel='tag' target='_self'>jbehave</a>, <a class='technorati-link' href='http://technorati.com/tag/kata' rel='tag' target='_self'>kata</a>, <a class='technorati-link' href='http://technorati.com/tag/tutorial' rel='tag' target='_self'>tutorial</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://giordano.scalzo.biz/2009/09/04/bdd-with-jbehave/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Private git repositories on Site5</title>
		<link>http://giordano.scalzo.biz/2009/08/28/private-git-repositories-on-site5/</link>
		<comments>http://giordano.scalzo.biz/2009/08/28/private-git-repositories-on-site5/#comments</comments>
		<pubDate>Fri, 28 Aug 2009 21:51:18 +0000</pubDate>
		<dc:creator>giordano scalzo</dc:creator>
				<category><![CDATA[tutorial]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[site5]]></category>
		<category><![CDATA[ssh]]></category>

		<guid isPermaLink="false">http://www.scalzo.biz/?p=12</guid>
		<description><![CDATA[It happens I have a shared host on Site5 and it happens most of kool koders are moving to git. I&#8217;m not a so kool koder, but I think git deserve a try. I know Github offers a wonderful service for open source projects, and I tried it for a bunch of pet works, but [...]]]></description>
			<content:encoded><![CDATA[<p>It happens I have a shared host on <a href="http://www.site5.com">Site5</a> and it happens most of kool koders are moving to <a href="http://www.git-scm.com">git</a>.<br />
I&#8217;m not a so kool koder, but I think <a href="http://www.git-scm.com">git</a> deserve a try.</p>
<p>I know <a href="http://www.github.com">Github</a> offers a wonderful service for open source projects, and I tried it for a bunch of pet works, but something is better to keep private, so, some month ago, I tried to set up a <a href="http://www.git-scm.com">git</a> repository on my <a href="http://www.site5.com">Site5</a> account without success.</p>
<p>Some day ago, I bumped into a <a href="http://mark.ryall.name/blog/2008/08/17/using-git-on-site5-the-details/">couple</a> of <a href="http://rwmj.wordpress.com/2009/03/06/git-fatal-no-matching-remote-head/">posts</a> and, finally, I reached my goal.</p>
<h4>Set up a password-less connection</h4>
<p><a href="http://www.git-scm.com">git</a> communication is based on ssh, but a password request each &#8216;git push&#8217; or &#8216;git pull&#8217; can be annoying in day-by-day working, so the first thing is to make our connection trusted by the server.<br />
In  <a href="http://mark.ryall.name/blog/2008/08/17/using-git-on-site5-the-details/">this post</a>, we can find detailed instructions for a Linux system:</p>
<pre class="brush: bash; gutter: false">user@localhost:~$ ssh-keygen -t dsa
user@localhost:~$ scp ~/.ssh/id_dsa.pub remoteuser@remotehost:
user@localhost:~$ ssh remoteuser@remotehost:
[remoteuser@remotehost ~]$ cat id_dsa.pub &gt;&gt; .ssh/authorized_keys</pre>
<p>For other OS, Google is your <a href="http://www.google.it/search?q=ssh+without+password+windows/">friend</a>.</p>
<h4>Create a repository on Site5</h4>
<p>Some month ago, all <a href="http://www.site5.com">Site5</a>&#8216;s servers <a href="http://www.site5.com/blog/s5/updated-git/20090422/">migrated</a> to the last version of <a href="http://www.git-scm.com">git</a> , but if you can&#8217;t find it installed, you can open a ticket: <a href="http://www.site5.com">Site5</a>&#8216;s support is always friendly and quick.<br />
Now we can create our repository:</p>
<pre class="brush: bash; gutter: false">[remoteuser@remotehost ~]$ mkdir -p git/repo.git
[remoteuser@remotehost ~]$ cd git/repo.git
[remoteuser@remotehost ~]$ git --bare init
[remoteuser@remotehost ~]$ exit</pre>
<p>and create our local repository:</p>
<pre class="brush: bash; gutter: false">user@host:~$ mkdir git
user@host:~$ cd git
user@host:~$ git clone ssh://remoteuser@remotehost/~/git/repo.git

user@host:~$ echo 'Here we go' &gt; README
user@host:~$ git add .
user@host:~$ git commit
user@host:~$ git push</pre>
<h4>Fixing “fatal: no matching remote head”-error</h4>
<p>After that, when I tried to push my modifies I got an “fatal: no matching remote head” error&#8230; fortunately I wasn&#8217;t <a href="http://rwmj.wordpress.com/2009/03/06/git-fatal-no-matching-remote-head/">alone</a> with that problem.<br />
First of all we need create an empty local repository then tell <a href="http://www.git-scm.com">git</a> that the &#8220;origin&#8221; of the local repository is the remote repository</p>
<pre class="brush: bash; gutter: false">
user@host:~$ cd repo
user@host:~$ git init
user@host:~$ echo 'Here we go' &gt; README
user@host:~$ git add .
user@host:~$ git commit -ma ''
user@host:~$ git push
user@host:~$ git remote add origin ssh://remotehost/~/git/repo.git
</pre>
<p>Then we have to connect the upstream &#8220;origin&#8221; with the current local branch:</p>
<pre class="brush: bash; gutter: false">vi .git/config</pre>
<p>and adding the following at the bottom:</p>
<pre class="brush: bash; gutter: false">[branch "master"]
  remote = origin
  merge = refs/heads/master</pre>
<p>Finally we have to synchronize remote with local repository:</p>
<pre class="brush: bash; gutter: false">git push origin master</pre>
<p>After that</p>
<pre class="brush: bash; gutter: false">git push</pre>
<p>and</p>
<pre class="brush: bash; gutter: false">git pull</pre>
<p>should work without problem</p>
<h4>Conclusion</h4>
<p>When discovered all necessary steps, any new repository installation goes smooth; in this post I tried to be complete and gather all the necessary informations.<br />
If you are new to <a href="http://www.git-scm.com">git</a> in <a href="http://blog.xebia.com/2009/01/26/git-101/">this</a> page you will find some useful links.</p>

<!-- start wp-tags-to-technorati 1.02 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/git' rel='tag' target='_self'>git</a>, <a class='technorati-link' href='http://technorati.com/tag/site5' rel='tag' target='_self'>site5</a>, <a class='technorati-link' href='http://technorati.com/tag/ssh' rel='tag' target='_self'>ssh</a>, <a class='technorati-link' href='http://technorati.com/tag/tutorial' rel='tag' target='_self'>tutorial</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://giordano.scalzo.biz/2009/08/28/private-git-repositories-on-site5/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

