Saturday, September 12, 2009

Hello JRack

Today Woody Zuill and myself put some of the finishing touches on a port of Rack to Java, and published it to the world. So let's do a quick show-and-tell to show you why we are so excited.

JRack is an extremely simple yet extremely useful and powerful way to create web apps.

Simple To Create
Let's look at how simple it is to create a "Hello World" web page.
public class HelloWorldRack implements JRack
{
public RackResponse call(Map<String, Object> input)
{
return RackResponseUtils.standardHtml("HelloWorld");
}
}



Wasn't that simple? Just 1 line to pass back the html we want displayed.

Simple To Run

Of course, this has just created it. What if we actually want to have this running on a Web Server, what would we have to do?

We can simply harness it through Jetty (you can also deploy on regular servers like tomcat). Jetty is a simple, standalone Web Servlet container. You can find out more about it here:

We'll add a main method to our HelloWorldRack:
public class HelloWorldRack implements JRack
{
...
public static void main(String[] args)
{
JettyUtils.startJettyRack(80, new HelloWorldRack());
}
}
Now, if we run HelloWorldRack, we will have a fully running rack server serving the HelloWorld page.
Nice and simple. You are up and running with just two lines of code.


Simple To Test & Reuse
But what if you unit test this code? Don't you need a webserver to even run it? NO!
You can call the RackApp directly. Simply pass in what in used by the environment (in this case, nothing). Whats more we've added approval test support so you can simple approve the resulting html.


Put this code into a JUnit test class:
public void testHelloWorld() throws Exception
{
Approvals.approve(new HelloWorldRack().call(null));
}
Okay - simple to write, simple to run, simply to test. There are many sites extolling the virtues of Rack. More and more, the Ruby community is migrating over to it. And now, you can have the same simplicity in the Java world. We'll write more about it later. You can download it here.
I also encourage you to look at the test examples here

No comments: