Friday 24 August 2007

Just in time compilation of GWT code

From Echo2 to GWT... I am still searching for the best toolkit.

What I liked at Echo2 is that the javascript code for the client is created just in time. There is no compilation step to be made before the deployment like in GWT.
GWT allows to develop an application in hosted mode, so probably there is no big need for a just in time compiler, because you will not deploy the application that often as with echo2 (does this make sense?).

Anyway, perhaps this feature may be useful for somebody.

The javascript code for the GWT client, which is normally deployed after compilation as static files, is produced in this example dynamically by a servlet. The servlet compiles the client code to javascript and caches it.

The source can be downloaded from
http://www.banapple.de/sandbox/JustInTimeCompilerServlet.java

What has to be done?


  1. The sources for the client have to be in the classpath of your web application.

  2. The os dependent GWT library containing the GWTCompiler has to be in the classpath.

  3. The servlet is defined to be accessible under the relative url /gwt-jit (or anything you want).

  4. The HTML page containing the GWT client has to include the GWT module using the servlet url, like in

    <meta name='gwt:module' content='/gwt-jit=de.banapple.MyModule'>




How does it work?

The servlet creates to directories under WEB-INF/. One for holding the
compiled files, one as a temporary directory for the compilation.

The GWT bootstrap code requests the file
/gwt-jit/de.banapple.MyModule.nocache.html.

The servlet first looks whether the file
de.banapple.MyModule.nocache.html
is already in the cache of compiled files.
If not the module is compiled in method handleModule. This method just uses the class com.google.gwt.dev.GWTCompiler, which stores the compiled files in the temporary compilation directory.

Afterwards the temporary files are copied to the cache directory. The GWTCompiler creates a directory with the module name in the temporary compilation directory. When the GWT bootstrap code requests further cache files (those files with names being a hash), the servlet can not determine which module they belong to and can therefore not look into directory named after the module (ok, it could, it would have to search all those module directories). So they are all copied flat into the cache directory, hoping that the filenames of different modules do not clash.

The servlet is definitely not fail-proof, e.g it will not work if two request come in which initiate the compilation. But as a first shot it worked for me.