What I hate about Wicket Framework

This post describes my opinion about Wicket framework.

Wicket is a component-based Java web framework from Apache that is gaining some popularity. Like most component-based web frameworks, Wicket is harder to learn than controller-to-view frameworks (Request-based) like Grails, Stripes, Servlets/JSP, Rails etc., but it offers more features and is more focused on the state of HTML elements instead of the state of HTTP requests. (Update 7-July-2010: to be clear, I don’t think controller-to-view frameworks are better, I just think they are easier to learn. But when you need to develop a WebApp, I think component based frameworks make the development easier.)

It’s not that I hate Wicket, but there are some features that I don’t like:

Heavily based on sessions.

Although Wicket does offer a few stateless components and session-less features, it is heavily based on sessions. Without session, state-fullness is difficult. Sessions have two drawbacks: timeouts and memory consumption.
A timeout occurs when a user doesn’t respond within (usually) 30 minutes. When that happens, the state of the page the user visited is lost. There are some Ajax hacks around this, but they are cumbersome. An option is to increase the timeout, but then you will be limited by memory consumption of sessions.
Some argue that memory is cheap, but that depends on your situation. If you’re building some in-house Website/webapp for a  company running its own servers than memory is indeed cheap. If you are a student or a freelance developer that is deploying the website on some leased VPS (Virtual Private Server) or a dedicated server, than the memory usage can increase the costs a lot.
What I like is the solution of Microsofts ASP.NET framework. It uses viewstates instead of sessions, which stores state in hidden html elements that are submitted back to the server when the user triggers an event, by using Javascript. This approach also has some drawbacks, but it doesn’t depend on sessions.

Wicket team had plans of implementing “client-side models for zero-state scalability”, but unfortunately they dropped it.

High learning curve

Component-based frameworks (pull MVC) are more difficult to learn than controller-to-view based frameworks (push MVC). This makes documentation more important, but the recommended book Wicket in Action doesn’t provide much inside in about how Wicket exactly works. This makes it difficult to do a bit more than standard stuff, when after you have read it.

Wicket URLs

I hate it when URLs reveal the usage of a framework. Wicket has Url Coding Strategies to fix this, but when using statefull pages, these urls often reveal the Wicket framework, this because Wicket uses the url to track a version of a web page. For example, you might get URLs like:
http://example.com/product/abc/.1.2 and when you click on some component on that page that will let you stay on the page but which some updated components, then you get http://example.com/product/abc/.1.3
The unwanted part is .1.3. It should stay http://example.com/product/abc all the time.

When clicking a component, there also often is an unwanted extra HTTP redirect before fetching the final HTML.

HTML is not that pure

A philosophy in Wicket is that HTML should strictly be separated from code and component properties, so that a web designer can make the HTML, and the programmer can just code Java. I hate the idea of making it easier for a web designer (highly subjective opinion), since I’m a programmer that makes the HTML/CSS myself, but I like the idea of separating it cleanly. But when using Wicket you will get a lot of tags like this in your HTML when you  need to repeat components:
<wicket:container>……</wicket:container>
So the HTML isn’t that pure.
If you don’t use that container element, than you easily get two nested divs where only one div is needed.

Update 11-July-2010: the commenter “anonymous coward” showed unwanted divs can be prevented by using setRenderBodyOnly. Other not-pure HTML can occur when Wicket Fragments are used, but this scenario doesn’t happen often.

Static component tree

It would be nice if you can create a tree of components dynamically, but in Wicket you have to define the tree structure statically in both the HTML layout and the Java code. It is possible to switch subtrees, but those subtrees have to be defined upfront.

Very verbose

Because of the clean separation of html and Java, and because it’s a component based framework, code will be more verbose than standard push MVC framework. A feature of Wicket that makes it even more verbose is the use of “models”. Model objects can be used by components to retrieve data, so that there is a clear distinction between data and data retrieval. This becomes clear when using repeating elements in HTML. Then you usually need to define LoadableDetachableModel anonymous classes that are nothing more than packed method calls to your DAOs (Data Access Objects) to retrieve data.

What I do like

This blog post is focused on what I don’t like, but to give you a short idea of what I do like:

——————–

Update 7 July 2010: changed “complexity” to “high learning curve”. And wrote more explicitly that I do favor component based frameworks over controller-to-view/request based frameworks, like the commenters below also do.

Update 11 July 2010: changed my opinion about “Not pure HTML” after the post of the commenter “anonymous coward”.

Java Error 1723

Background & Problem:

Because I have a lot of Firefox plugins installed, Firefox became pretty slow, so I had some plugins disabled, under which a plugin for running applets. Yesterday, I came on some page that required applets, but the plugin was missing, so I let the browser install it automatically. After that, I was unable to start Java. Trying to reinstall or uninstall Java, gave the error 1723.

System specs:

-Windows 7 64 bit
-JDK 6.18 32 bit

Googled Solutions:

Using Google I found some proposed solutions:

  • http://www.javafixer.org/error-1723.php, doing the Regedit fix damaged the Windows Installer, and Windows Installer 5.0 (needed for Win7) cannot be download from the Microsoft site. So this solution didn’t work for me.
  • JavaRA: http://raproducts.org/. If you try this, don’t forget to run it under administrator. This solution didn’t work for me.
  • RegCleaning by using for example http://www.piriform.com/ccleaner. Also didn’t work.
  • Install Visual C++ 2005 Redistributable Package (x86). Didn’t work.
  • Windows Installer CleanUp Utility from the Microsoft site. Didn’t work.
  • Manually deleting JDK files. Didn’t work.

What did work for me:

On some forum (out of the many that discuss about this irritating error), I found someone that fixed it by removing all “jre” related from the registry. This did it for me :) Open regedit, and search for “jre” and look for keys (directories) that contain “jre” values (fields) that are related to Java. Delete those keys.

After doing this, the JDK installer ran without problems, and without mentioning about existing installations.

Wicket – Sending a 301 redirect

This post describes how to send a HTTP 301 redirect in the Java Wicket Framework.

HTTP redirect intro

There are two types of HTTP redirects:
-”HTTP 1.1 301 Moved Permanently”
-”HTTP 1.1 302 Found”, previously called “HTTP 1.1 302 Moved Temporarily”

A 301 indicates that the requested resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs.
Where a 302 indicates that the requested resource resides temporarily under a different URI.

For a normal web browser it doesn’t matter which type of redirect is send to the browser, because the result is the same: the user is redirect to a different URI. But for Search Engines (SE’s) it does (or might) matter, at least if you want the correct URL to be indexed. If you’re using a 301, than you’re telling SE’s that they should use the new URI. If you’re sending a 302 then you’re telling that they should use the old URI.

301 using Wicket

In Wicket, you can send a 301 using:

getRequestCycle().setRequestTarget(new RedirectRequestTarget("/path/to/legacyJspFile.jsp"));

302 using Wicket

The problem is that the redirect method always uses a 302. If you want to perform a 301, you can use this code, which overrides the respond method:

RedirectRequestTarget target = new RedirectRequestTarget(url) {
  @Override
  public void respond(RequestCycle requestCycle) {
    WebResponse response = (WebResponse) requestCycle.getResponse();
    response.reset();
    response.getHttpServletResponse().setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    response.redirect(url);
  }
};
getRequestCycle().setRequestTarget(target);

This will cause the RedirectRequestTarget.respond(RequestCycle requestCycle) method to be called, which will get a WebResponse object using the requestCycle object, and it will call the WebResponse.redirect(String url) to set the redirect.

More info:

  • http://wicket.apache.org/docs/1.4/
  • http://www.w3.org/Protocols/rfc2616/rfc2616.txt
  • http://cwiki.apache.org/WICKET/how-to-redirect-to-an-external-non-wicket-page.html

Grails vs. Rails

Ruby On Rails and Grails are two popular MVC webframeworks. Rails uses the Ruby language, and Grails uses Groovy. In this post I compare Grails vs Rails.

Introduction

Ruby On Rails (in short just “Rails”) is a webframework that uses the Ruby language. It uses a push MVC design pattern, which means that a controller/action receives a client HTTP request, then creates or search (in a DB) for model objects containing data, and forwards those objects to the view where a HTML page is rendered for the HTTP client.

The other webframework, Grails, is also a push MVC webframework that uses some ideas of Rails. In fact, it was previously called Groovy On Rails. Grails uses the Groovy language instead of Ruby.

About the comparison

The way I look at these frameworks is influenced by my prior knowledge and preferences:
-I have a Java background
-I strongly prefer static typed over dynamic typed. (Why would you hide important information in your code about types if you need to document it anyway.)

I’m not an expert in these frameworks. Maybe I don’t even know the existence of some basic features. So if you think I forgot to mention something important, then leave a comment :)

Grails and Rails, in common

  • Development, production and test modes.
  • built-in webserver
  • quick boot/startup
  • hot deploy / class reloading without restarting the server
  • ORM (Object Relational Mapping) / Active record
  • lots of plugins, that can be downloaded from the command line. a plugin manager
  • nice URLs
  • model, view, controller, and test generators
  • popular, an active community
  • easy to learn / use
  • The language supports: string interpolation, multi line strings, raw string (no Java escape hell), closures
  • Full stack frameworks
  • screencasts
  • console for additional testing
  • easy to configure
  • productive
  • Builders. Configuration can be done in Groovy/Ruby files that look like normal configuration files. Easier to read than XML.
  • Books are available
  • quick releases
  • Dare to drop features. Can be good or bad, but I like it when features are dropped in order to keep the framework good.
  • Build tasks
  • Very easy to create tags/reusable HTML components. (Something you cannot say about JSF.)
  • Convention over Configuration

Grails vs. Rails

  • Documentation. The first thing that frustrated me about Rails was documentation. How do you learn Rails? Grails has an excellent up-to-date User guide, but on the Rails doc webpage you have API, Books, some outdated not-working external third-party tutorials, and how-to’s. But no userguide….. It’s very frustrating when you are halfway your first Rails steps in a tutorial (that is directly linked from the official main Rails docpage), and find yourself having to Google for solutions/workarounds because the popular Rails tutorials are so outdated that it doesn’t work anymore. If you want good learning material, you are forced to buy a RECENT (e)book otherwise you’ll find code that doesn’t work.

    API documentation is probably better in Rails than Grails because they have examples and more info in it. Rails also has wiki pages, which can be useful when looking for specific problems. Grails on the other hand has a userguide/tutorial that is very suitable for beginners, it is also useful for a quick reference. Grails website has some pages that have duplicated info about the same subject, sometimes these pages are outdated, and thus conflicting each other. e.g. the Grails pages about validation.

  • Grails uses other solid frameworks underneath it, like Hibernate and Spring. Frameworks that are well known in Java enterprise. These frameworks have a lot of features for the Model and controller, and thus give Grails a lot of features.
  • The View layer in Rails has a lot of features; there are a lot of view helpers/functions, which can be very handy. e.g. link_to_unless_current, which creates a hyperlink to an URL unless it is already the URL of the current page. Another example is Rails’ RJS, which allows you to write Ruby code that is outputted in Javascript.

    But Grails has IMO too less helpers. On this point, Grails is very weak compared to Rails. e.g. a select html input in Grails doesn’t allow selecting more than one item. Also, implementing error textfield highlighting using default Grails tags is very cumbersome.

  • Both frameworks are popular and have an active community. Rails is more popular; it existed before Grails and has inspired other frameworks. Rails has more jobs.
  • Grails automatically adapts the DB when creating/changing model attribute names, but this feature might be a bit unstable sometimes, since updating existing model classes is not very stable in Hibernate. (It is hard to determine whether a new found attribute is a new attribute or a renamed existing attribute when no versioning is used.) (Hibernate can also generate Java classes from an existing DB.)

    Rails uses Migrations to change the DB. A migration is a Ruby file containing almost SQL-like commands; it’s like writing pure SQL, but you have to write it yourself. Every migration has a version, and commands to change versions, so Rails has a DB versioning system. This can be very useful when you need to update the Production servers’ DB in a consistent way.

    Grails has a more object oriented approach; it shields/protects you from low-level sql. Where Rails gives you more SQL control when creating tables, and Rails allows you to control db versions.

  • Grails has GORM (Grails Object Relational Mapping) for making, saving and retrieving the domain models from the database. Rails uses Active Record.

    Grails (GORM) uses Hibernate (one of the best ORM frameworks) underneath its layers. When making a model class in Grails, you make a plain basic class with the attributes defined in it. When making relations between model classes, you’ll have to use special variable names that define the relations. Like belongsTo, hasMany, mappedBy and embedded. Maybe this can be done with Groovy annotations in the future? Grails automatically saves adaptions you make to a model class, to the db. Although, as mentioned previously, it uses Hibernates hbm2ddl, so for safety, you have to check manually that the DB table is what you expected when changing/renaming existing attributes. Validation of attributes is also put in the model class.

    Rails Active Record differs a lot from Grails GORM. A Rails domain class/entity is composed of two files, a migration file and a Rails model class file. All model attributes and datatypes are defined in the migration file and/or database, using an SQL wrapper. So that the migration files can be directly translated to pure SQL; writing a migration file is like writing SQL DDL (CREATE statements). At this point the associated Rails model class file is empty. From an Object Oriented point of view, this is an ugly approach; the attributes are defined in SQL/db instead of the domain model class itself. It also makes IDE autocompletion and refactoring hard. It also makes it cumbersome for yourself to lookup the attributes for a domain model class; you have to look in multiple files for it! Making relations is done both using SQL foreign keys and is similar to Grails, putting special variable names or methods in the model class: belongs_to, has_many etc. Validation is also done in the model class. When you add new attributes to a model, you can use a new Rails Migrations to propagate it to the DB. Which basically is a SQL change table add column command.

    So the Domain model in Rails is database based, instead of OOP based like Grails. I know OOP and Hibernate, so I like starting with OOP for the domain model and generate the DB from it. Btw Hibernate can do both; it can reverse engineer/generate Java classes from an existing DB, and it can generate the DB from domain model classes.

  • Both have books available. Rails has more books.
  • Grails has Implicit Dynamic Scaffolding (optional), you don’t have to write the view. The view (html) is generated, and changes automatically when you add new properties to the model. This can be useful when learning the framework. But when coding a webapp, you probably write the view yourself. Rails had Implicit Dynamic Scaffolding in the past, but they removed it because it’s only useful for beginners. Both frameworks also have explicit scaffolding.

    I prefer the scaffold generated by Rails, but Grails has column sorting.

  • Grails uses Groovy, so you can use new or existing Java classes/libraries, and thus have both dynamic and static typed. You can even code pure Java in Groovy classes, or mix them. Rails uses Ruby, but Rails also has third party JRuby, which allows you to call Ruby classes from Java classes and back. JRuby is less integrated with Java than Groovy. Like Grails, with JRuby you can run a web-app in a Java EE environment. JRuby is probably only interesting for those who want to use existing Java classes.
  • Grails is faster than Rails, but with JRuby, Rails can increase its speed. The ruby Merb framework (similar to Rails) will be merged with Rails in the future. Merb is faster than Rails.
  • In Rails, it’s very easy to pass objects from the controller to the view, because of Ruby. For example in Rails:
    		Rails:
    		*** ProductController ***
    		@product = Product.find(1)
    		@category = Category.find(1)
    		

    In Grails you have an extra step with duplicated names.

    		Grails:
    		*** ProductController ***
    		product = Product.find(1)
    		category = Category.find(1)
    		['product' : product, 'category' : category] // last line in controller action. It defines an identifier twice.
    		
  • Rails has a lot of different names for the same thing, which can be confusing. This is caused by Rails pluralization; controller names and db tables are automatically named in plural from a singular name. For example, when you have a domain class for a shipping address. In Rails you’ll find names:
    • ShippingAddress (model classname)
    • shipping_address (model filename, attribute name)
    • shipping_addresses (controller filename, attribute list name, db table and migration name)
    • ShippinAdresses (controller classname)
    • Pluralization can be turned off, but is enabled by default, it’s the Rails way of naming.

  • Grails uses Jetty as default webserver in development mode. Rails uses Mongrel by default, and Webrick in the past.
  • When generating a Grails project, the project will still use some script files from the Grails_home dir. Rails copies these files, which makes it easier to adapt Rails projects without influencing other projects.
  • Grails uses Java underneath it; it uses more memory than Rails. This probably makes hosting a Rails app cheaper than a Grails (Java) app. (Hosting can be cheap when you use a Virtual Private Server.)
  • Grails has an expression language, like JSP. In a Grails view, you can use:
    • <%= product.getPrice() %>, or
    • ${product.price}

    Rails doesn’t have an expression language, so you can only use <%= product.price %>. I prefer using expression language when possible; it keeps the view cleaner.

  • Grails uses Groovy, which IMO is easier to learn than Ruby, especially is you already know Java. Groovy uses a syntax that is found in other languages, like C++, Javascript and PHP. Ruby however differs from that. Also, in Ruby, there are often multiple ways to do something. Sometimes the language remove one way, while leaving the other. This can be confusing. Ruby, also has no method overloading.
  • Rails feels more matured than Grails because of it’s better View layer. It also is already at version 2.2 where Grails is at 1.0.
  • Rails has a built-in benchmark, profiler. Grails has it using third party plugins.
  • Both Grails and Rails configuration files are easy to read. Grails probably has an easier syntax.
  • Rails inspired other frameworks, like Grails.
  • Rails seems to be released/updated more often. This might be because Graeme Rocher (a Grails developer) was working a Grails book the last couple of months.

Specific for Rails:

  • Easy to change from a single Rails version on a system shared by multiple projects, to a single Rails per project config. So that you can run multiple Rails versions if needed.
  • Very REST by default. nested url resources like /articles/1/comments/5/edit
  • security, authenticity_token against cross site request forgery.
  • You need to restart the webserver when you add a scaffold for a model, because routes.rb gets changed.
  • Rails’ Active Record uses a lot more SQL in code than Grails (Hibernate).
  • Changes in routes.rb requires a restart. Thus adding new resources (like REST controller for a model) requires a server restart.
  • The DB drives the Model. E.g. default model values have to be specified in the DB.
  • Cumbersom to find how you can code in Model classes as Plain Old Ruby Objects. For example you can’t use the initialize method?
  • Rails with Capistrano and Mongrel make it easy to implement load balancing. Not sure if this is also possible with Grails.
  • Rails has special url_path variables/methods, which makes writing urls easier. For example, it automatically has variable/methods names like edit_article_url(article) that translate to the correct URL.

Specific for Grails

  • Grails: Sitemesh breaks the OSIV (Open Session In View) pattern. So you cannot use full GORM in layouts. Something that really needs to be fixed.
  • No Java annotations in Groovy?
  • (Groovy) console/shell tool cannot work with def keyword?
  • Hard to debug errors messages
  • doesn’t work out of the box with all third party servlet based software. For example, UrlRewriteFilter doesn’t work.
  • less secure? Via a html form POST hackers can set properties for new objects even is those properties aren’t defined in the form itself. (This happens when the new MyDomain(params) is used.) FIX: use command objects or bindData method. Not sure if Rails has a better solution.
  • Jsession id’s are sometimes visible in the url. e.g. when using the flash for messages.
  • Grails: Looking up a pretty url given a controller and action and id, isn’t possible? Only the default url scheme is used?

Summary and my preferences:

  • I like both Grails and Rails.
  • I prefer the Groovy language over Ruby, especially because Groovy supports static typed and Java. Although writing in Ruby is also cool.
  • Grails really has to do something about the view layer. Rails is a lot better at this point.
  • I dislike that Rails domain model is database centered. I doesn’t feel object oriented. You cannot use plain Ruby classes, you have to look in the migrations for model attributes. You cannot simply use an initialiser/constructor of the model in Rails, for example when you want to set default values. How do you make a constructor that receives parameters? Ruby also doesn’t support method overloading. The Rails domain model feels limited in a OOP way.
  • Rails feels more matured.
  • Grails is more enterprise and Java EE focussed, using Spring and Hibernate.
  • Grails focusses on the use and incorporation of other well known frameworks using plugins, making it possible to use other webframeworks if needed. For example: Struts, Wicket, Flex, GWT and Echo.
  • Rails project configuration is more flexible.
  • I should have a better look at JRuby.

Shorter Grails textField

Making textFields in Grails is a bit verbose, at least if you want error highlighting and returned values on errors. This post shows a quick solution.

Problem

A full textField would be:

<g:textField class="${hasErrors(bean:user, field:'name', 'errors')}" value="${fieldValue(bean:user,field:'name')}" name="name"/>

Which clearly is very verbose; you have to specify “user” twice, and “name” even three times. This verbosity also makes the view less readable.

Googling for this problem resulted in: Smarter Grails Tags (a proposal). Funny that the writer exactly sees the same problem in it, also uses the “user” domain model, and also knows Stripes where you could just use something like

<stripes:text name="name"/>

and specify the bean name in the form. (Stripes has a very good Quick Start Guide, which also shows error highlighting.)

One of the less verbose proposed formats of textField is:

<g:textField bean="user" field="username" />

Implemented Solution

I found that implementing a quick version of this is surprisingly easy in Grails, it only takes for a few statements. Here is the code:

import org.codehaus.groovy.grails.plugins.web.taglib.FormTagLib

// file: project/grails-app/taglib/MyTagLib.groovy
class MyTagLib {
    // tagname "myTextField" within the "g" namespace
    def myTextField = {attrs ->
        // If a controller returned the bean, and the field has an error,
        // then "errors" will be returned as HTML class, otherwise the class will be empty.
        attrs.class = hasErrors(bean:attrs.bean, field:attrs.field, 'errors')
        // Retrieves the field value of the given bean to be rendered in the view.
        // Note: specify the bean and not the bean name. So "${user}" instead of "user"
        attrs.value = fieldValue(bean:attrs.bean, field:attrs.field)
        // Required for textField taglib. attrs.name is a keyname of the params map
        attrs.name = attrs.field
        // renders the HTML tag
        out << new FormTagLib().textField(attrs)
    }
}

Usage

<g:myTextField bean="$user" field="name" />

And ofcourse some CSS to highlight the error in a color. This can be put in the HTML head (or better, a seperate CSS file) :

<style type="text/css">
   .errors {
      background-color: red;
   }
</style>

Grails and existing Java Hibernate DAO’s

If you have some existing Java Hibernate entity classes (outside Grails), you only have to add one line in Datasource config, and you can use them immediately. However, if you have some exising POJO (Plain Old Java Object) Hibernate DAO’s (classes that implement a Data Access Object pattern), you’ll have to do some additional steps to make it a bit suitable.

(The solution described in this post can also be handy when you need data access on places where GORM is NOT available. GORM not available? Yes, GORM is not fully available when you access collections via a taglib that is accessed via a Sitemesh layout. (A scenerio that isn’t rare.) (Should be considered as a bug?) In that case you will get a lazily initialize a collection error. If you use HibernateUtil, you can get around this by just opening new session yourself.)

Existing Hibernate entities and GORM

You can use existing Hibernate Java entities directly in Grails. The only thing that you’ll have to configure is:

  1. define mappings in hibernate.cfg.xml
  2. set GrailsAnnotationConfiguration as configClass in DataSource.groovy

For example:
webapp/grails-app/conf/hibernate/hibernate.cfg.xml :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <mapping class="myPackage.Product"/>
        <mapping class="myPackage.Customer"/>
        <mapping class="myPackage.Supplier"/>
    </session-factory>
</hibernate-configuration>

webapp/grails-app/conf/DataSource.groovy :

import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration

dataSource {
    configClass = GrailsAnnotationConfiguration.class
    pooled = true
    driverClassName = "com.mysql.jdbc.Driver"
    url = "jdbc:mysql://localhost/mydb"
    username = "myusername"
    password = "mypass"
    dbCreate = "create" // one of 'create', 'create-drop','update'
    dialect= org.hibernate.dialect.MySQLInnoDBDialect
}
hibernate {
    cache.use_second_level_cache=true
    cache.use_query_cache=true
    cache.provider_class='com.opensymphony.oscache.hibernate.OSCacheProvider'
}

Now you can put your existing Hibernate java entities in webapp/src/entities (or any other package), and they will work immediately and have GORM functionality.
For example, in the Grails controller classes, you can direcly use Product.get(100) (to get a Product instance that has id 100). Hibernate sessions and transactions are created/invoked automatically.

Exising Hibernate DAO’s

If you don’t need any GORM functionality and you don’t want Grails to touch sessions, then you can use your existing unaltered full hibernate.cfg.xml.

However, if you have some POJO DAO’s that use the HibernateUtil helperclass, you will have to do some additional steps to make it a bit suitable. (In this example, I use the configurations above.)

By default Grails injects a SessionFactory
First, your DAO’s will need a HibernateSession to perform work. By default Grails injects a SessionFactory into Grails controllers that have a “sessionFactory” variable defined. So the following controller will automatically have a SessionFactory available:

import org.hibernate.*;

class ProductController {
    // This one will be injected
    SessionFactory sessionFactory

    def index = {
        Session session = sessionFactory.getCurrentSession()
        println session.createQuery("from Product").list()
    }
}

(You can also use Gorm in this controller example and don’t use the SessionFactory yourself, but this just to show that a SessionFactory will be injected.)

HibernateUtil used by the DAO’s
In the example, the DAO’s use HibernateUtil to get a SessionFactory. By default HibernateUtil create a SessionFactory itself, but the SessionFactory provided by Grails is needed instead, so we alter HibernateUtil slightly:

package persistence;

import org.hibernate.*;

public class HibernateUtil {
    private static SessionFactory sessionFactory;

    public static SessionFactory getSessionFactory() { return sessionFactory; }
    public static void setSessionFactory(SessionFactory sf) { sessionFactory = sf; }

    public static void shutdown() { sessionFactory.close(); }
}

Set SessionFactory for HibernateUtil
We want HibernatUtil to be ready with a SessionFactory after booting, so we configure HibernateUtil during the bootstap. We alter webapp/grails-app/conf/BootStrap.groovy to:

import persistence.HibernateUtil
import org.springframework.web.context.support.WebApplicationContextUtils

class BootStrap {

     def init = { servletContext ->
        def ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)
        def sf  = ctx.getBean('sessionFactory')
        HibernateUtil.setSessionFactory(sf)
     }

     def destroy = {
         HibernateUtil.shutdown()
     }
}

Now the DAO’s can use HibernateUtil.getSessionFactory().getCurrentSession() to get a HibernateSession.

Microsoft Access and informative id keys

(Programmers usually don’t use Microsoft Access in multi user apps, but it can be handy if you quickly need to setup some single user personal administration database.)

A thing that I find very cumbersome in Access, is the use of surrogate keys (e.g. autonumbering IDs instead of business keys like “name”), because autonumbering keys are not very informative. This blog post tells you how you can show informative field while at the same time keep using your existing surrogate keys.

Tested with Microsoft Access 2007.

Example of the problem

Here an example of the problem: you have a STUDENT table and a COLLEGE table, where a student has only one college, and a college can have multiple students. (A one-to-many relation.)

Now when you want to select/assign a college to a student, you don’t want to select it using NON-informative college_id’s like this:

instead you want select college_id’s using informative college names like :

And after after selecting the college_id, you want the informative college fields to stay visible in the list, like this:

while at the same time having a transparant relationship using the numbered surrogate id’s as foreign keys.

Composed of two subproblems

The problem consists of two sub problems:

  1. selecting non-informative foreign key id’s transparently using informative fields.
  2. showing (single or multiple) informative fields in the list instead of a non-informative foreign id key

Solution using Lookup Wizard

The easiest way to accomplish this is to use the “Lookup Wizard”. This wizard creates a (new) relationship between the 2 tables, so you have to make sure that a relation doesn’t exist yet.
In this case, college_id will be the foreign key and thus the lookup column.

There are two ways to access the Lookup Wizard:

  1. via the “Lookup Column” button. This creates a new column, so college_id shoudn’t exist yet. Or
  2. by selecting “Lookup Wizard” as “Data Type” for college_id.

The wizard is self-explanatory. When selecting the column in this wizard, make sure you select BOTH the id, AND the columns that you want to be visible. You also have an option to hide the ID, which can be enabled if you prefer.

After finishing the wizard, you’ll see that you can now use informative fields instead of non-informative id’s, while transparently maintaining a foreign key relation using the non-informative id’s.

Manual solution

If you don’t to use the Lookup wizards, you can do it manually yourself in the field properties of college_id:

  1. change the “Display Control” to “List Box” or “Combo Box”
  2. set “Row Source Type” to “Table/Query”
  3. set “Row Source” to a query that contain BOTH the foreign key (college_id) AND the data that you want to be visible as value (cname in this case). The id column MUST be the first column, even if you don’t want it to be visible.
  4. set “Column Count” to the number of columns of the query from step 3
  5. set “Column Widths” for the columns. The ugly part: it is important that you set 0 as width for the id, so that it will be skipped and not be visible in the row, and thus the second column will be visible, which is our informative column.

Multiple informative field in the list

The text above only partially solves subproblem 2; it shows ONLY 1 informative field, even when you selected multiple informative field in the wizard.
For example, it shows

where only “MyFirstCollege” is visible instead of also the value “Rotterdam”. Instead we want:

where the “location” field of the COLLEGE table is also visible.

A manual solution to show multiple informative field in a row (like the last picture), is to concatenate the fields. This can be done by going to the field properties of college_id in the STUDENT table, and alter the SQL query:
SELECT COLLEGE.ID, COLLEGE.cname, COLLEGE.location FROM COLLEGE;
to
SELECT COLLEGE.ID, COLLEGE.cname & ‘-’ & COLLEGE.location FROM COLLEGE;

Grails & Jetty with multiple contexts

A webapp usually contains both dynamic resources (scripts, config files, html files) and static resources (jpg, zip files, data etc). These resources can be deployed all together as one package, but when you have a lot of static resources, you usually want them to be seperate from the dynamic resources. Reasons might be that you have that much static resources that it will slow down deployment or testing when packaged as a single unit, or you might want static resources to be served by a seperate service to improve performance, or you might want them to be in seperate filesytem hierarchy because the static resources might also be needed outside the webapp. In this post I describe two methods to solve the problem of seperating dynamic from static resources when using Grails and Jetty.

The methods are tested using:

  • Grails 1.0.3
  • Jetty 6.1.4 (default Jetty for Grails 1.0.3)
  • Static Resources 0.5 plugin

Method 1: Static Resources plugin & symbolic links

The Grails Static-Resources plugin is designed to separate dynamic from static resources.

Install:

  1. open a cmd/shell prompt and go into the directory of your Grails webapp project. I will call this directory <myapp-grails-project-base>.
  2. type: grails install-plugin static-resources
    The plugin will now be installed for the current webapp only.

I’ll show by example how the Static-Resources plugin works. Suppose you have a website called example.com and a webapp called myapp, then the webapp is available at http://example.com:8080/myapp/. When you have the plugin installed, everything under the /static/ (filesystem directory) will be available under http://example.com:8088/ when run in dev environment. Notice that port 8088 is used instead of port 8080. The plugin does this by starting a NanoHTTPD, which is a lightweight single class Java HTTP server. The plugin calls this the resource server.
When you go to http://example.com:8088/, you will get a directory listing of all the files located in the static directory, so you can start using them and linking to them, but there is a better way (read on).

If you put a pdf file at <myapp-grails-project-base>/static/archive/catalog2005.pdf (filesystem) then it will be available automatically and directly at http://example.com:8088/archive/catalog2005.pdf in a dev env.
You can hardcode links to http://example.com:8080/archive/catalog2005.pdf manually in the view, but you can also use the plugins dedicated resourceLinkTo tag for this. For the pdf link, this tag is used as: <g:resourceLinkTo dir=”archive” file=”catalog2005.pdf”/>

When running in prod env instead of dev, the resourceLinkTo tag will link to the URI /resources/archive/catalog2005.pdf instead of http://example.com:8080/archive/catalog2005.pdf. And this time it won’t start a NanoHTTPD server, it only changes the link. So in a prod env, you have to map /resources/ to <myapp-grails-project-base>/static/ yourself, in whatever production HTTP server you are using. You could do this in Tomcat 6 by putting something like <Context docBase=” <myapp-grails-project-base>/static/” path=”/resources”/> in the host element of server.xml, or better, in context.xml.

If you don’t want your resources to be located in the <myapp-grails-project-base>/static/ directory, you can use symbolic links in the static directory, and map them to elsewhere. Note that symbolic links are not only available on POSIX systems (Linux etc), but also on Windows systems using special tools. (I’m not talking about Windows Shortcuts, but Windows symbolic links, hard links or junctions.)

Another way is to change the static directory location by modifying <myapp-grails-project-base>\plugins\static-resources-0.5\grails-app\services\ExternalResourceServerService.groovy.

Method 2: a second Jetty webapp context

The static resources method (described above) doesn’t have a complete built-in solution for a production environment; you have to make/map the /resources/ URI yourself.

If want you to use Jetty in both dev and prod env, or if you want to have a separate static resources directory without using the Static-Resources plugin, then read on:

1) Open %GRAILS_HOME%\scripts\RunApp.groovy
2) change

    target( configureHttpServer : &quot;Returns a jetty server configured with an HTTP connector&quot;) {
    def server = new Server()
    grailsServer = server
    def connectors = [new SelectChannelConnector()]
    connectors[0].setPort(serverPort)
    server.setConnectors( (Connector [])connectors )
    setupWebContext()
    server.setHandler( webContext )
    event(&quot;ConfigureJetty&quot;, [server])
    return server
}

to

    target( configureHttpServer : &quot;Returns a jetty server configured with an HTTP connector&quot;) {
    def server = new Server()
    grailsServer = server
    def connectors = [new SelectChannelConnector()]
    connectors[0].setPort(serverPort)
    server.setConnectors( (Connector [])connectors )
    setupWebContext()

    server.addHandler( webContext )
    WebAppContext resourceContext = new WebAppContext(&quot;D:/myapp-grails-project-base/static&quot;, &quot;/resources&quot;)
    server.addHandler(resourceContext);

    event(&quot;ConfigureJetty&quot;, [server])
    return server
}

Now, everything under D:/myapp-grails-project-base/static will be mapped to http://…../resources, in both dev and prod evironment, and will be served seperate from the webapp.

A drawback of placing this in RunApp.groovy is that every Grails app will have a /resources context running next to it.

Note that Jetty 5 and earlier versions of Grails probably needs different code.

Edit:
Grails maintains a temperary directory for scripts in %userhome%\.grails\1.0.3\scriptCache. I you find that modifications aren’t visible, then try deleting that directory.

More info:

Struts2 table annoyance

I was trying out a bit of Struts 2 just to test it out. An annoyance that quickly came up is that the HTML layout of forms are all table based. For example, if you want an input field for your name, then a column-based HTML table will be created automatically for that. The first column contains a HTML label, and the second the input field.

For example, the following Struts2 code:

<s:form action="HelloWorld">
    		<s:textfield name="name" label="Your name"/>
    		<s:submit/>
		</s:form>

will yield this HTML code:

<form id="HelloWorld" name="HelloWorld" onsubmit="return true;" action="/StrutsInAction/chapterTwo/HelloWorld.action" method="post">
	<table class="wwFormTable">
		<tr>
			<td class="tdLabel"><label for="HelloWorld_name" class="label">Your name:</label></td>
			<td><input type="text" name="name" value="" id="HelloWorld_name"/></td>
		</tr>
   		<tr>
			<td colspan="2"><div align="right"><input type="submit" id="HelloWorld_0" value="Submit"/></div></td>
		</tr>
	</table>
</form>

What if you want to work without HTML tables? Or what if you want to put a label on the first row and its input field on the second row, instead of using two columns? You can by using the “simple” theme instead of the default “xhtml” theme. Set it using:

<s:form action="HelloWorld" theme="simple">

The generated HTML code will now be:

<form id="HelloWorld" name="HelloWorld" onsubmit="return true;" action="/StrutsInAction/chapterTwo/HelloWorld.action" method="post">
	<input type="text" name="name" value="" id="HelloWorld_name"/>
	<input type="submit" id="HelloWorld_0" value="Submit"/>
</form>

But…. using the simple theme, will drop validation, error reporting, ajax etc……

So if you don’t want those column based HTML tables but do want the default framework functionality (validation etc), you will have to make your own themes……

JSF doesn’t have this problem, there you could just write something like:

<h:form>
	<h:outputLabel for="name">Your name:</h:outputLabel>
	<h:inputText value="#{formAction.name}"/>

This is a bit more coding then using Struts 2, but it gives you the flexibility to place the outputLabel wherever you want, instead of being locked to two HTML columns.

More info:
http://struts.apache.org/2.x/docs/themes-and-templates.html
http://www.vitarara.org/cms/struts_2_cookbook/creating_a_theme

Seam-gen and default ROOT context

If you are using seam-gen to deploy webapps as war-files to a webserver (for example JBoss AS), the root url of your webapp will be something like http://example.com/myproject/. (Where “myproject” is the name that you gave to your webapps when setting it up using seam-gen.) If you want your webapp to be assigned to the root (http://example.com/) (also known as the default ROOT context), then read on.

To change the root context, I perform the following steps. Note, there might be a better way, but this one works for me. If you’re using ejb instead of war, then you probably have to do some additional steps.

Tested using jboss-4.2.2.GA and jboss-seam-2.0.2.SP1.

1) After creating the project, open build.xml. Change

<property name="war.dir" value="exploded-archives/${project.name}.war" />

to

<property name="war.dir" value="exploded-archives/ROOT.war" />

and change

<property name="war.deploy.dir" value="${deploy.dir}/${project.name}.war" />

to

<property name="war.deploy.dir" value="${deploy.dir}/ROOT.war" />

2) Go to the following directory: {your.jboss.home.dir}\server\default\deploy\jboss-web.deployer. And rename ROOT.war to something else. The JBoss manager might then not be available anymore.

3) Now run an explode, and your webapp will be at the ROOT context.