December 28, 2007

Java SE 6 developer preview released for OSX Leopard

It looks like Apple has quietly released Java SE 6 for Leopard through their Apple Developer Connection. The release is only for Leopard (10.5.1) and requires 64-bit Intel Macs (sorry PowerPC and 32-bit Intel based machines).

September 17, 2007

Waffle and JRuby: Accessing parameters and attributes from request, session and servlet context

In the last post I quickly explained how easy it is to access a component registered with Waffle from your JRuby based controllers. Now we need to understand how to access GET and POST parameters in order service a visitor's request. This is easily done through the parameters variable (also aliased as params) on your Ruby based Controllers. This variable is a simple Hash, so looking up parameter values from your Actions as easy as:
def example_one
foo = params['foo'] # request parameter
return "<h1>FOO: #{foo}</h1>"
end

Accessing Request, Session and ServletContext attributes

It might also be useful to access attribute values from either javax.servlet.ServletRequest, javax.servlet.http.HttpSession or javax.servlet.ServletContext. This is, as you should expect, very easy to do. But Waffle automatically wraps each of these as a Ruby Hash. This provides the correct Ruby "feel" when writing your Actions. The following code snippet give an example of how you can access attribute values from each of the 3 contexts:
def example_two
foo = params['foo'] # request parameter
fuu = request['fuu'] # request attribute
bar = session['bar'] # session attribute
baz = application['baz'] # servlet context attribute
return "<h1>FOO: #{foo} FUU: #{fuu} BAR: #{bar} BAZ: #{baz}</h1>"
end
Additionally, you can also call any of the Java methods these instances provide (you are NOT limited to methods exposed by Hash).

Auto-resolve values

Now those of you familiar with Waffle realize that Waffle provides a built-in means to auto-resolve a variables value. Waffle will search each of the following (in order) until the value is found, otherwise null (or in the case of JRuby nil) will be returned:
  1. HttpServletRequest Parameter (HttpServletRequest.getParameter("foo"))
  2. HttpServletRequest Attribute (HttpServletRequest.getAttribute("foo"))
  3. HttpSession Attribute (HttpSession.getAttribute("foo"))
  4. ServletContext Attribute (ServletContext.getAttribute("foo"))
  5. return nil

So with that in mind we can simplify the previous example down to one line. Waffle will attempt to resolve the value of any unknown variable through this means. The following shows the previous method simplified because it relies on Waffle auto resolving each value:
def example_three
return "<h1>FOO: #{foo} FUU: #{fuu} BAR: #{bar} BAZ: #{baz}</h1>"
end
In my next blog post I'll begin discussing how you can integrate JSPs or even RHTML with your applications.

September 14, 2007

Waffle: How to access your Java components from your Ruby Actions.

In my last post I gave an overview of how you can easily integrate JRuby with Waffle. Now we will examine Ruby based controller in a bit more depth. Lets assume we have the following Waffle Registrar for our application:
public class MyRegistrar extends AbstractRubyAwareRegistrar {

public MyRegistrar(Registrar delegate) {
super(delegate);
}

@Override
public void application() {
register("the_dao", PersonDAOImpl.class);

registerRubyScript("person", "PersonController");
}
}

A DAO, PersonDAOImpl, is registered under the name "the_dao" and we have one Ruby based controller available. Now its probably safe to assume that this Ruby PersonController will need access to the DAO. Gaining access to this DAO from the controller is easy in Waffle, just call the locate method:
class PersonController

def index
@person_dao = locate(example.PersonDAO)

@people = @person_dao.findAll
render 'person.rhtml'
end

end

Notice that we were able to retrieve the DAO by its interface. Additionally, since this DAO was registered with a key you can use a convention to retrieve the component. The convention is "locate_<component key>", here is the same controller using the locate_ convention:
class PersonController

def index
@person_dao = locate_the_dao

@people = @person_dao.findAll
render 'person.rhtml'
end

end

As you can see this makes writing Ruby based Controllers/Actions with Waffle really easy. In my next post I'll detail how to access request parameter and context attributes with ease.

September 12, 2007

Ever wish you could utilize Ruby from your Java based web applications?

Waffle, a Java based Web Framework, now provides built in support for JRuby. This will allow you to easily write your Controllers in Ruby. The integration is simple and straightforward, taking advantage of functionality Waffle provides (without being a Rails clone).

A key feature of Waffle has always been its pluggable architecture. From the beginning we believed that the default behavior defined by the Waffle team might not be suitable for every situation. Therefor Waffle was built following an Interface driven approach. Practically all of Waffle's built-in functionality can easily be extended or replaced. This design made integrating JRuby support quite easy. The next 3 steps give a brief overview of how to integrate JRuby support into your Waffle based applications.

Step 1 - configure Waffle to be "Ruby Aware"

Waffle avoids XML like the plague but we still need to have a web.xml for our applications. This web.xml is where we can take advantage of Waffle's pluggability. The following three context-param nodes need to be added to your applications web.xml. This alerts Waffle that a few of its foundational components should be replaced with alternate implementations.
<context-param>
<param-name>org.codehaus.waffle.context.ContextContainerFactory</param-name>
<param-value>org.codehaus.waffle.context.pico.RubyAwarePicoContextContainerFactory</param-value>
</context-param>
<context-param>
<param-name>org.codehaus.waffle.bind.DataBinder</param-name>
<param-value>org.codehaus.waffle.bind.RubyDataBinder</param-value>
</context-param>
<context-param>
<param-name>org.codehaus.waffle.controller.ControllerDefinitionFactory</param-name>
<param-value>org.codehaus.waffle.controller.RubyControllerDefinitionFactory</param-value>
</context-param>

Step 2 - Your application's Registrar should extended AbstractRubyAwareRegistrar. This exposes a new registration method to use within your Registrar ... registerRubyScript(String key, String className). See the example below:
public class MyRegistrar extends AbstractRubyAwareRegistrar {

public MyRegistrar(Registrar delegate) {
super(delegate);
}

@Override
public void application() {
registerRubyScript("foobar", "FooBar");
}
...
}

In this example the Ruby class named 'FooBar' will be exposed as a Controller under the name 'foobar' (e.g. http://localhost:8080/jruby/foobar.waffle).

Step 3
- Write your Ruby Controller class. Notice in the following example that your class does not need to extend or include anything.
class FooBar

def index # This is the default action
"<h1>Hello World</h1>"
end

end

And that is all the steps required to integrate JRuby within your Waffle Applications. In my next post I will uncover details on how to access registered components from your Ruby based controllers as well as explain the built in conventions that make writing Ruby controllers so easy.

September 10, 2007

Argible: impromptu presentation at chirb

Tonight I ended up giving an impromptu overview of Argible at the monthly Chicago Area Ruby Group. Utilizing annotations in Ruby code seemed foreign to several of the folks there. So, I quickly went over the Argible source code to illustrate how annotations can be implemented in Ruby (via the Module#method_added(name) callback). This code alone seemed to interest several of the people there.

Additionally, I tried to stress that the concept of using an argument name as meta-data is what I personally find most interesting about Argible. The idea behind Argible should NOT be limited simply to Rails based applications. Anyone have ideas for other situation where this might be useful?

Shoes: Cross-platform Ruby GUI Toolkit

Tonight I attended the monthly Chicago Area Ruby Group. A fellow ThoughtWorker, Josh Cronemeyer, gave an overview of Why's Shoes project.

Many of the attendees seemed to question the need for a Ruby based HTML-like GUI toolkit. While Shoes is by no means ready, nor possibly even intended for, business applications I did find it interesting. A viable Ruby GUI toolkit would improve Ruby adoption even further. Of course JRuby and Swing integration could be sufficient enough to fill that gap (i.e. Swiby).

August 30, 2007

Are your Java projects misusing java.text.Format?

As a consultant with ThoughtWorks I get the opportunity to see many different code bases at a variety of client. A common mistake I see again and again is that developers do not realize that sub-classes of java.text.Format (e.g. NumberFormat, SimpleDateFormat) are not thread safe. If your project defines a static instance of a formatter, like so:
public static final SimpleDateFormat SIMPLE_DATE_FORMAT 
= new SimpleDateFormat("MM-dd-yyyy");

Then chances are you have a bug.

As is the case with many threading issues, this might not be easily identified because it probably doesn't happen consistently (we are at the mercy of the Thread Scheduler).

Recently on a project I created a test to prove that using such Formats can cause problems. We then fixed the issue and decided to keep the test in the code base to ensure that no developers 'accidentally' re-introduces it. NOTE: A Continuous Integration server, CruiseControl, ensures that our tests are run continuously.

Below is a simple, self-contained, test you can use to see the issue for yourself. Remember that the test might not fail every time because it is dependent on how the threads are scheduled. I have found that the test fails with more consistency when executed a single CPU (or single-core) machine.

import junit.framework.TestCase;

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

public class ThreadSafetyTest extends TestCase {
private static final SimpleDateFormat FORMAT
= new SimpleDateFormat();

public void testSimpleDateFormat() throws InterruptedException {
for (int i = 0; i < 50; i++) {
MyRunnable[] runnables = {
new MyRunnable(new Date(-1)),
new MyRunnable(new Date(1))
};

Thread one = new Thread(runnables[0]);
Thread two = new Thread(runnables[1]);

one.start();
two.start();

one.join();
two.join();

assertFalse("Values should not be equal",
runnables[0].value.equals(runnables[1].value));
}
}

private static class MyRunnable implements Runnable {
private Date date = null;
public String value = null;

MyRunnable(Date date) {
this.date = date;
}

public void run() {
value = FORMAT.format(date);
}
}
}

August 29, 2007

Argible: testing argible-ized actions

Last week Jay Fields and I were discussing Argible and he asked, "How's testing an action that uses Argible?", the answer ... easy.

Suppose we have the following Controller with an argible-ized action:

class CalculatorController < ApplicationController

argible(:first => :to_i, :second => :to_i)
def add(first, second)
@result = first + second
end

end

And here is the associated RSpec test:

describe CalculatorController, "add action" do
controller_name :calculator

it "should add argument values" do
post :add, :first => "18", :second => "2"
controller.instance_variable_get(:@result).should == 20
end

end

You can see from the test that you do not need to do anything special to test your argible annotated action methods. Just call the action with whatever parameter name and values your action requires.

August 22, 2007

Blogger.com: unable to edit a post without publishing

Today I went back through my blog and added some labels (aka tags) to older posts. Soon afterwards I realized that adding these labels forced those post to be re-published. I found this annoying because visitors to sites like ThoughtBlogs would now have to sift through this "noise", obscuring the most recent post I'm most interested in sharing.

I think Blogger.com should provide a way to make minor edits to previously published posts without forcing these posts to be re-published. I understand that WordPress offers this functionality (right?). Is there a way this can be done that I might have missed? Or would I need to wait for such functionality to be introduced? Maybe it'll be easier if I just move my blog WordPress?

Argible: automatically set instance variables

As I discussed in my last post Argible makes it easy to resolve method argument values through simple convention. Peter Ryan had an excellent idea of using Argible to automatically set an instance variable's value through simple convention. Have a look at the example below:

class MyController < ApplicationController

argible(:foo => :@bar)
def action_one
p "Bar instance variable was set to: #{@bar}"
end

end

Notice that the action method, action_one, has NO arguments. But the argible annotation was passed :foo => :@bar. Argible will interpret that you want the resolved value of 'foo' to be set upon the instance variable named '@bar'. This happens because the symbol on the right hand side is prefixed with the character '@'. Without this Argible will raise an Error informing you that there is no such argument.

August 20, 2007

Introducing Argible: Simplifing your Ruby on Rails Controllers

Argible is a RubyForge project that was created to simplify Action methods within your Ruby on Rails Controllers. Argible annotated action methods will allow your Actions to define argument. These argument names will be used in conjunction with request parameters to automatically resolve these argument values. Have a look at the FoobarController code below:

class FoobarController < ApplicationController

argible
def action_one(alpha)
...
end

argible(:date => Date.method(:parse))
def action_two(date)
...
end

argible(:date => lambda {|v| Date.parse(v) } )
def action_three(date)
...
end

argible(:value => :to_i)
def action_four(value)
...
end
end

The first method action_one(alpha) is annotated with the method argible. When the action_one method is executed Argible will intercept the call and look up the request parameter value associated with alpha. Next the action_one method will be called with this resolved value.

The second action, action_two(date), provides an example of how more complex processing can occur on argument values. As in the first example the argument, this time named date, is resolved against the request parameters. The resulting value will then be passed to the Date#parse method. The result from Date#parse will then be used when action_two is called. **NOTE: any method can be used, Date#parse is simply used as an example.

The action action_three(date) provides an example of using a Proc (lambda) as alternative to a named method.

The fourth example action action_four(value) illustrates how you can call methods directly on the string value returned from
the request parameter.

Argible 0.1.0 is available for immediate use from http://rubyforge.org/projects/argible. RDoc can be found at http://argible.rubyforge.org.

July 26, 2007

Run your JRuby RSpec tests from Maven

On my most recent project we made heavy use of RSpec. After 6+ months of using it I must admit that I am a big fan. Therefor I was very happy to see that JRuby included RSpec within its distro (see JRuby bundles RSpec).

I have also been working on adding JRuby support for Waffle. So I decided to write my Ruby tests for Waffle with RSpec. Additionally, I wanted these RSpec tests to run as part of the build. Waffle, like many Java open source projects, uses Maven 2. Regardless of whether you love or hate Maven its dependency and repository convention have became a standard way to easily distribute jars. So I wrote an Maven plug-in that allows you to execute your RSpec tests from Maven. We have since contributed this to Codehaus' Mojo Project. So give it a look if you have the need.



** Ruby support within Waffle will allow developers to write their Controllers, and other objects, with straight Ruby syntax. Look for more info on this functionality soon.

May 22, 2007

Waffle Haus ...

Waffle is moving from SourceForge to Codehaus. Additionally, and more importantly Waffle and VRaptor teams have decided to join forces.

The Waffle web framework will provide the core architecture for this joint effort. As the first step we have has begun porting Waffle to Codehaus (renaming it to use org.codehaus.waffle package instead of com.thoughtworks.waffle). Next we will begin to gradually port features from VRaptor. The vision of this effort is to create a larger and more consolidated community around a lean web application framework which honours the least-common-denominator principle.

March 20, 2007

RSpec:Rails - How to mock partials when testing a View.

When developing Ruby on Rails (RoR) applications I prefer to use RSpec over the built in testing framework provided with RoR. The biggest benefit is that RSpec easily allows you to test your application layers in isolation (e.g. when testing a Controller you should not be interested in testing the Model). So with that in mind when I am testing a View I am only interested in testing that View and not any of the potential partials that View may try to render.

Suppose we have the View /example/hello_world.rhtml:

<div id="person">
<h2 class="title">Hello <%= @person.name %></h2>
<%= render :partial => 'address', :locals => {:person => @person} %>
</div>

Often in RSpec when testing a view such as this the spec ends up testing the partial as well. This is less than desirable because any change to the partial could break test for other views that render that partial. After some investigation I discovered that I could mock the calls to <%= render :partial => 'address'... %>. Have a look at the following spec:

specify 'should call mock and not the actual partial' do
person = mock('person')
person.should_receive(:name).and_return('Regan')
assigns[:person] = person

# Mock the call to 'render_partial'...
@controller.template.should_receive(:render).with(:partial => 'address', :locals => {:person => person})

render '/example/hello_world'
response.should_have_tag(:h2, :content => "Hello Regan")
end

You can grab a handle to the ActionView through @controller.template as is done in the example above. Then I mock the call to the 'render' method only when the 'address' partial is requested.

As you can see my spec only needs to be concerned with testing the /example/hello_world.rhtml View. The partial will have it's own separate spec. The side effect is that my view specification becomes much more manageable and far less brittle.