Stripes Book from the Pragmatic Programmers

July 23, 2008

It's really good to see a book being published by the Pragmatic Programmers on the Stripes, even if it is too little, too late. I wrote an article on Stripes a few years ago, and actually, I still like how Stripes handles mapping request parameters to an object graph, but since then I have discovered the benefits of dynamic languages like Ruby, so I would never consider using a framework like Stripes, just because it means programming in Java. When I was doing Java, I felt that Stripes was a much better framework than WebWork/Struts, but for some reason flew under the radar. In fact, this blog is built using Stripes. Stripes' creator Tim Fennell always did an excellent job answering questions on the mailing list and deserved more recognition from the Java community as a whole.

It's surprising to see this book coming out now. Frankly, straight Java as a web development language is yesterday's technology, the Cobol of our generation. The JVM is still alive an well, with many great options, such as JRuby, Groovy, Scala and the best of them all, Clojure. I would love to see a Pragmatic Programmer book on Clojure, just to give some more attention to Clojure, because it is such a great language. Anyway, congrats to Tim Fennell, Frederic Daoud and the Stripes team on finally getting some acknowledgment for building a great framework and a great community.

Posted in Technology | Tags Stripes, Java, Clojure | 8 Comments

Guice Hello World

March 12, 2007

A new project called Guice (pronounced Juice, but starts with a G instead of J because it's Googlerrific) has been created. Guice aims to be a better Dependency Injection (DI) framework for Java. The de facto DI framework for Java is currently Spring. Spring provides a lot of things besides DI, but I think DI is it's main selling point. I often use Spring in projects only for it's DI. I use Stripes as my Web MVC framework and Hibernate as my ORM framework, so I don't need Spring's MVC layer or JDBC Template. I do use Spring's declarative transaction management and hibernate configuration features, but that's only because once you start using Spring for DI, it's easy to use those features as well, but they could be easily replaced.

The main disadvantage of Spring, in my opinion, is the amount of XML files that you have to create to configuration you application. The thing I dislike most about the XML configuration is that it is not type safe, and just like Bob Lee says:

I'm using a strongly typed language; why would I want to throw all of this perfectly good type information away? If I wanted that, I'd use Ruby.

I don't think he meant that statement as a knock against Ruby, he's just saying that if you are programming in Java, then you want to use type safety as much as possible. Annotations and Generics, features added to Java in Java 5, can allow you to do that, and Guice aims to provide dependency injection via Annotations rather than XML.

So I decided to take a look at Guice, and although the documentation is pretty good, it doesn't have a working "Hello World" type example to get you going, so I figured I would provide one here. I encourage you to play along at home.

First, download Guice, setup a new project in your favorite IDE, and add guice-1.0.jar to your classpath. What we're going to do is create a basic domain model object, Foo, and a DAO-like Manager for Foo, and then create a controller that depends on the FooManager, and has that dependency set using Guice. So here we go. Create the Foo class:

public class Foo {

    private Long id;
    private String name;

    //Generate and getters/setters in your IDE

}

Then create the interface for the FooManager:

public interface FooManager {

    public Foo get(Long id);
    public void save(Foo foo);

}    

Then create an implementation of the FooManager. In real life, you might implement this with an ORM framework like Hibernate, but this simple little thing serves the purpose for this example:

public class FooManagerImpl implements FooManager {

    private static Long fooSequence = 1l;
    private static final Map<Long, Foo> foos = new HashMap<Long, Foo>();

    public Foo get(Long id) {
        return foos.get(id);
    }

    public void save(Foo foo) {
        if(foo == null) return;
        if(foo.getId() == null) {
            foo.setId(fooSequence);
            fooSequence++;
        }
        foos.put(foo.getId(), foo);
    }
}

And for the last part of our app, we'll create a controller that calls our manager. This controller is sort of like what a controller in a web app might be like:

public class FooController {

    private FooManager fooManager;

    //----- Controller Actions -------------------------------------------------
    public Foo create(String name) {
        Foo foo = new Foo();
        foo.setName(name);
        fooManager.save(foo);
        return foo;
    }

    public Foo retrieve(Long id) {
        return fooManager.get(id);
    }

    //----- Getters/Setters ----------------------------------------------------
    public FooManager getFooManager() {
        return fooManager;
    }

    @Inject
    public void setFooManager(FooManager fooManager) {
        this.fooManager = fooManager;
    }

}

You can see that with the annotation Inject on the fooManager setter, we are asking Guice to inject a fooManager instance into our controller. Continuing with the web app like architecture of our app, we'll create a dispatcher. In a real app, this would be the FrontController responsible for directing the request to be handled by the appropriate controller action, but for our simple app, we'll just hard code 2 controller action methods to be called:

public class FooDispatcher {

    public static void main(String[] args) {

        FooController controller = new FooController();
        Injector injector = Guice.createInjector(new FooModule());
        injector.injectMembers(controller);

        //Our action is now injected with a FooManager, so let's use it
        Foo foo = controller.create("Bar");
        Foo bar = controller.retrieve(foo.getId());
        System.out.println("bar.name => "+bar.getName());

    }

}

As you can see here, we've now got some Guice specific code. First we create an injector using the FooModule. The FooModule is a class we create that serves as the configuration for Guice, we'll get to that in a minute. The creation of this injector is something that you would do once, probably upon application startup. Then, we ask the injector to inject our controller instance with its dependencies. The simple Inject annotation we added on the setFooManager method of our controller is all the info the injector needs to set up our controller. Next you see we call 2 action methods, one to create a new Foo instance, and then another to retrieve it.

So let's look at the FooModule, which is where we do our Guice configuration:

public class FooModule extends AbstractModule {

    protected void configure() {
        bind(FooManager.class)
            .to(FooManagerImpl.class)
            .in(Scopes.SINGLETON);
    }

}

What this says is that when something needs a FooManager injected into it, use a singleton instance of FooManagerImpl to fulfill that dependency. We can actually use annotations to further simplify this configuration. First, we add the ImplementedBy annotation to the FooManager interface:

@ImplementedBy(FooManagerImpl.class)
public interface FooManager {

    public Foo get(Long id);
    public void save(Foo foo);

}

This basically says to Guice that we want FooManagerImpl to be the default implementation class for FooManager. Also, we can specify that by default we want FooManagerImpl to be a singleton:

@Singleton
public class FooManagerImpl implements FooManager {

    private static Long fooSequence = 1l;
    private static final Map<Long, Foo> foos = new HashMap<Long, Foo>();

    public Foo get(Long id) {
        return foos.get(id);
    }

    public void save(Foo foo) {
        if(foo == null) return;
        if(foo.getId() == null) {
            foo.setId(fooSequence);
            fooSequence++;
        }
        foos.put(foo.getId(), foo);
    }
}

Now, we can modify our module to look like this:

public class FooModule extends AbstractModule {

    protected void configure() {
        bind(FooManager.class);
    }

}

An now when we re-run our FooDispatcher, every thing still works. In real life, there would be some core mechanism in the web app framework to handle creating the injector and injecting dependencies into the controller instances, and I'm sure it would be fairly trivial to implement that into Stripes.

Although some people don't think Guice is going to replace Spring, I think for projects where Spring is being used mostly for DI, we will see Guice or something like it start to replace Spring. I also predict that in response to this, Spring will be forced into incorporating an annotation-based configuration mechanism into its core codebase in order to remain popular in the oncoming wave of Annotation based "zero" configuration frameworks like Stripes, Struts 2 and Hibernate.

UPDATE: Monday, March 12, 5:18pm

Thanks to a tip from Bob, I've discovered that once you have every thing configured by annotations, as we do at the end of this example, you can completely remove the FooModule, which gives you the code like this in the dispatcher:

public class FooDispatcher {

    public static void main(String[] args) {

        FooController controller = new FooController();
        Injector injector = Guice.createInjector();
        injector.injectMembers(controller);

        //Our action is now injected with a FooManager, so let's use it
        Foo foo = controller.create("Bar");
        Foo bar = controller.retrieve(foo.getId());
        System.out.println("bar.name => "+bar.getName());

    }

}

The point is that for any class that you can configure with annotations, you don't need to explicitly define them in a module, or anywhere. So take an app with 50 different manager classes, all you would have to do is create a manager interface, annotate it as a singleton, and then create the default implementation. Compare that with a minimum of 50 bean entries in a Spring context configuration XML file, and you can see how Guice can really start to simplify your configuration.

Posted in Technology | Tags Spring, Hibernate, Stripes, Java, DependencyInjection, Guice | 28 Comments

PaulBarry.com 3.0

January 28, 2007

So I've finally finished the latest version of my site. The first version of my site went online on March 3rd of 2006 using WordPress. Then on my last birthday, I switched to Typo. Now, I've got up the first version of my site that I have built myself, using Java, Stripes, Spring and Hibernate. I'm using Resin as the Web/Application server and MySQL for the database. The OS is Ubuntu and it is hosted with VPSLand.

I hoping that this version will be more stable than the previous version. If you are having any problems using the site, let me know.

Posted in Technology | Tags Resin, Spring, Hibernate, Stripes, MySQL, Java, Ubuntu | 6 Comments

Back from the Beyond

October 20, 2006

So as I said I would, I've taken a look at Python and Django. In my brief look at it, I've learned a few things. One is that Python isn't that weird, it's just different. Handling blocks based on indentation is cool. Django is cool in a lot of ways. The thing I was most impressed with is the admin interface. The thing I was least impressed with is that the admin interface isn't very customizable. You get you what you get, which is a lot, but you don't have much control over it.

But this blog post isn't really about Python or Django specifically, it's about languages and web frameworks. Here's what I've decided. Choosing a web framework and programming language is like choosing a guitar. There are die hard fans of different types. There are obscure niche types. There are widely used types. There are even variations among the different types. But the bottom line is that if you are a shitty guitar player, it's going to sound like shit, not matter which one you pick. And if you are a great guitar player, anything is going to sound pretty good. Choosing between them is really a matter a preference. The part where this analogy falls apart is that once you learn to play guitar, you can pick up any guitar and play, but just because you are a Ruby on Rails expert doesn't mean you can build a web site with Java, and vice versa. So it's not perfect, but you get the idea.

I think up until recently, you couldn't argue with a straight face that building a Java application is not more complicated than building a Ruby on Rails app. Anyone who has tried to maintain a web app built with Struts 1.x, Spring, Hibernate 2.0, JSP 1.0 and an overly complex set of ant build scripts can attest to that. But I'm a believer in the latest innovations in Java. Annotations and Generics are making life easier. Stripes and Hibernate 3.2 with Annotations are much better than Struts (or webwork or Spring MVC for that matter) and Hibernate 2.0 respectively. JSP 1.2 is better than JSP 1.0, Maven is better than Ant, the list goes on.

My theory is that we are at a point with Java where we can build applications with the same level of productivity as any other framework. I think we're beyond Beyond Java.

So what I'm planning on doing in attempt to prove Bruce Tate wrong is to build a new version of my own blog in Java. I'm hoping this little side project will give me a chance to provide the world with an example of how Java applications can be built without endless XML sit-ups. I also feel the need to blog about it because it will motivate me into actually doing it. I have had lots of big ideas in the past and I rarely follow through with any of them, but this is one that I intend to. And so it begins.

Posted in Technology | Tags Django, Python, Stripes, Ruby, Java, Rails | 16 Comments

Stripes is the new Rails

July 11, 2006

I've have recently discovered Stripes, a Java web MVC framework. I know what you're thinking, yet another Java web framework? Struts, Webwork, Tapestry, Wicket, RIFE, do we really need another framework? I think the answer is yes. From my experiences with the Stripes framework, it seems like it has the simplicity and flexibility of Rails, without the limitations. What are the limitations of rails you ask? There are two that I can think of off hand:

  1. Indexed Properties

    It is very difficult to work with index and nested properties in Rails. In simple terms what I mean by indexed and nested properties is being able to have a form field called bugs[0].watchers[3].name, which means you have a list of bugs, and each bug has a list of watchers, and each watcher has a name, and you want to get/set the name property of bug #1, watcher #4 (the indexed are zero-based, like arrays). Stripes makes this easy, it seems to be much more difficult in Rails.

  2. Dealing with non-AR model objects

    Rails lacks the concept of a data binder. In Java, Spring MVC, Webwork and Stripes all have this. In the Java frameworks, if your form contains a field called user.firstname, it assumes you must have an object called user that has a property called firstname that you want to bind that value to. You bind the values to Plain Old Java Objects (POJOs), and they you can do whatever you want with the object.

    In Rails, the controller stores the request parameters into a data structure that is a Hash of Hashes, so the request parameter user[firstname] becomes { "user" => { "firstname" => "whatever" } }. Then, the base ActiveRecord class has a constructor that takes that hash as a parameter and sets the properties of the object based on the hash. But there are two problems with that. First, if your model objects don't subclass ActiveRecord, then you don't have that functionality. Second, if you have nested objects, it can't create them as necessary, you have to do that.

The Stripes framework is very easy to pickup and I found the author of the framework to be very helpful on the mailing list. Stripes gains most of its simplicity by relying on Annotations and conventions to limit the amount of configuration necessary. You only add a few things to your web.xml and then everything else is handled by annotations, there is no stripes.xml or whatever, as almost all other frameworks have.

I think there are a lot of similarities between Webwork and Stripes and I'm sure there will be even more similarities between Stripes and Struts 2.0, once it is available.

Posted in Technology | Tags Struts, Stripes, Ruby, Java, Rails, WebWork | 0 Comments