Monday, November 28, 2011

Grails 2.0 - the power is back

Recently I've been bitching about the stability of Grails 2.0 and specifically the lack of it. Tons of stuff was just wrong: the new GSP parser was buggy like hell, hot-reloading using the new agent just didn't work - you name it. But with the RC1 release most of it is gone and the new version of Grails starts to look like something you could actually use!

Hot reloading.

Since its early days Grails was the number one framework and that in most part due to its hot-reloading capabilities. You could just change a view, controller or service, wait just a few seconds and the result would emerge after refreshing the page. That presented a huge advantage over classic Java EE development where a single change in the code forced the developer to recompile and restart the whole application. That's why I hate regular Java EE development with a passion. Sure there's the Java Rebel thingy but it costs money - a lot of money!

Grails 2.0 uses a different approach than the one in 1.x series but a similar one to Java Rebel. There's a Java agent that does all the heavy lifting of incorporating new code into existing application. So let's summarize what works and what doesn't:

- reloading controller - check
- reloading services - check
- reloading url mappings definition - check (with the exception of mapping to HTTP codes)
- reloading domain classes - not working
- reloading Groovy sources under /src/groovy - check!
- reloading Java sources under /src/java - check!

There might be other areas but the general impression is really awesome!

New scaffolding templates


Well.. they are nice and green and dandy and... well I liked the old ones better (from the general look-and-feel point of view). The new ones still use the word "main" for everything: CSS, template and the application.js. Does anyone knows who made that stupid decision to call "main" or "application" something that should be called "scaffold"??? In the current state of things if you're thinking about doing anything serious with Grails you should install the templates and rename them to something that makes sense, like for example main.gsp -> scaffold.gsp or main.css -> scaffold.css. Other than that it's looking really good! Just the fricken naming...

Resources and other capabilities


Well, finally the resources plugin made it into the core! So from now on the problems like having lots of small JavaScript or CSS files and cramming'em together for the release version are gone. This is probably the only platform out there (besides ASP.NET :D) that does it right from the start. Granted it doesn't come for free - you need to configure it properly and it can be an unpleasant experience all along (unlike in ASP.NET where it's actually a part of the page itself). But at the end of the day it is really useful and you should use it.

Also the Datasources plugin found its sibling in the new release! This will be a blessing for everyone that needs to work with multiple databases in their Grails applications. In the databases plugin configuration was "almost" like the one you'd normally have but different enough to make you curse the creator more than once. I'm delighted to say that this has been unified and finally all datasources can be specified in the same configuration file, DataSource.groovy. Yay!!!

And last but not least - testing. Finally someone took the hard dependency on old 3.x JUnit and flushed it down the toilette! Man that was really what I was looking for. All test cases are now JUnit version independent and use the coolest Groovy feature ever: Mixins!
Finally testing domain classes in isolation is possible and doesn't make you puke at the mockDomain() call every time you see it. Finally the power is back!

Plugins


I've received some notifications that the plugin architecture has change a bit and that some of my plugins (namely the json-rest-api) don't work properly. It's sad but not unexpected. The general idea is that plugin authors will have to take a good look into regression before they can 'certify' their plugins as 2.0-ready.

Summary


The general feeling of Grails 2.0 is really great. Finally playing around with most of the UrlMappings is simple and fast (which it wasn't in 1.x), testing is fun again (even with Spock and the like) and all the rest is just great. So I guess the final message should be "go and use and forget about 1.3.7 that has been around for like ages".

And finally I really need to get this out of my chest: when it comes to regular Java EE development like with JSF (outch), Struts or what have you one should really go kick some corporate butts to get them to start thinking again that web development shall not be a nightmare anymore. We have the technology, you know, to make it right for a change!

Go spread the word!

Sunday, November 6, 2011

Why using a plain-text editor is a good thing

For the past years there's been a boom on the market for web applications. Along with that the possibilities for supporting technologies grew like never before. This has a two-fold implication.
First it is imperative that we recognize the need to write less and do more - that's where the new languages come in. Second it is obvious that new languages tend to emerge a lot faster than companies would like them to and as a result the fat IDE support is missing.

Obviously enough it's going to make for a strong case for plain-text editors (probably with some syntax highlighting like the good old vim or emacs). Those editors don't bother making deep sense of what the code really is. All they care about is that it is text.

"But I need refactoring support to be productive" you might say. Well, refactoring in new languages tends to be a lot less tedious than in (for example) Java where changing a file name leads to all sorts of changes that need to happen just to do this simple thing. New languages like F# for example (which is not all that new if you take into account its roots) have some refactorings kind of built in into the language and most plain-text editors support it out of the box. I'm talking here about method extraction and the way the Tab key works in most modern editors on more than one line of text.

In addition to that many new languages give you the power of succinctness never seen previously in specific areas. Take CoffeeScript or LessCSS for example. With those two new languages you can put together code in such a manner that when compared to the original language you'd write it in (JavaScript and CSS) can cause your head to explode.

At the end of the day it is up to you if you want to write more with (for the most part) good IDE support or if you're ready to give up some of that luxury in favor of more readable and less error prone code. But remember: the less code you have the less bugs you're going to have and that alone should make you want try out the latest inventions.

Have fun!

Sunday, October 16, 2011

Hazelcast and Grails

If you'll ever find yourself in need to partition your Grails application in order to provide high or availability or if you're lucky enough in order to increase processing power because your database is already not the bottleneck (which it will be for a long long time) then you should definitely check out Hazelcast and its Hazelcast WM module. Configuration is dead simple (a few lines in web.xml) and the thing is capable of auto discovery using multicast so you just add instances of both the Hazelcast distributed cache as well as instances of your application and everything just works.

Man, it's been a while since I found a tool that just does the job no questions asked and Hazelcast definitely is one of them!

And live is good again :)

Creating standalone applications with Java and Maven

The challenge

In this installment we're going to take a look at what does it take to create a standalone Java application that's a little bit more sophisticated than the famous Hello, World. Let's start with the simplest example:
package org.example;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, world!");
    }
}
To compile and run this one we need to invoke the javac compiler, package it to some jar file (say example.jar), create a manifest file (or not..) and start the application passing on the proper classpath and class name that is the entry point to our application. This might look something like this:
java -cp . org.example.Main

The "proper" way

I know for a fact that Maven can be a pain in the ass if used by some inexperienced fellow that wanted it to do everything but didn't know how to ask for it. For example for tasks that Maven is good at like specifying dependencies using Ivy and Ant for it makes no sense, right? Well, you wish! I've seen those kind of nonsense a lot of time with pom.xml reaching out beyond the magic 100k boundary...

Instead of cranking up the heat I'd like to see people develop simple mojos solving one problem at a time and not resorting to ant or anything like it. But above all, for crying out loud, use what's already there to do the job!

Doing Spring in standalone Java application

If you can imagine how hard would it be to prepare a standalone Java application that uses external configuration, external libraries and resembles what users are already used to (the bin folder, the lib folder, maybe some conf or etc for the configuration files) you'll appreciate the fine job application assembler is going to do for you.

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>appassembler-maven-plugin</artifactId>
    <version>1.1.1</version>
    <configuration>
        <copyConfigurationDirectory>true</copyConfigurationDirectory>
        <configurationDirectory>etc</configurationDirectory>
        <repositoryName>lib</repositoryName>
        <repositoryLayout>flat</repositoryLayout>
        <programs>
            <program>
                <mainClass>org.example.Main</mainClass>
                <name>example</name>
            </program>
        </programs>
    </configuration>
</plugin>
That's pretty much it! All you have to do now is to call maven to do your bidding.
mvn clean package appassembler:assemble
Please note I didn't change anything in the application itself. Well that's because it's not a post about how to instantiate Spring in a console application but rather how to package everything so that it works as expected. You can take a look at a fully working example on GitHub.

Have fun!

Saturday, October 8, 2011

Eclipse hint: Aptana Studio

I know I wrote the other day that I don't use Eclipse and I don't when working with anything else that Java. You just can't get away editing Java code on any serious level in any plain-text editor because the language is not designed to do it (like Groovy or Ruby for example). Recently I've been doing some research on what's available out there in terms of plugins and I've stumbled upon Aptana Studio. Even though I don't plan to code in Ruby any time soon I've decided to install it and give it a try.

All things considered I have found the one piece of that "studio" that has convinced me that working with Eclipse might be fun: the Terminal window :)



Imagine you're working with your project and all of the sudden you need to do some command-line processing (for whatever reason). With Aptana Studio it's extremely easy: you just right click on a node in project explorer or package explorer and select Open in -> Terminal :D

Man I like those little discoveries that make my life easier...

Thursday, October 6, 2011

Gitorious - a working guide to install

Finally someone did a guide on installing Gitorious on Ubuntu 11.04 and it WORKS!!!

Go check it out at http://coding-journal.com/installing-gitorious-on-ubuntu-11-04/

Saturday, October 1, 2011

Using DWR with JBoss and EJBs

Today we're going to get our hands dirty with the Direct Web Remoting (DWR) library in conjunction with JBoss and the EJB mechanism.

The why

DWR is a powerful library for all things related to remote method calls using HTTP. It can serialize lots of things, use DTOs if provided but above all it does one thing so easy it should be forbidden: It allows you to create or retrieve an instance and call its method directly from your JavaScript. This is why I'll always favor DWR over hand-written mechanisms or misuse of REST libraries like RESTfully. REST is all about resources - Ajax not necessarily...

The how

We're going to use DWR version 3.0.M1 as this is the latest available in Maven repository at the time of writing. Creating the project itself is outside of the scope of this post however configuring the framework isn't so we're start with that.

web.xml


<!DOCTYPE web-app PUBLIC
  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <servlet>
    <servlet-name>dwr</servlet-name>
    <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
    <init-param>
      <param-name>debug</param-name>
      <param-value>true</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>dwr</servlet-name>
    <url-pattern>/dwr/*</url-pattern>
  </servlet-mapping>
</web-app>
As you can see here this is pretty much the basic that you'd expect from a web application that has one servlet in it. The other stuff will be done using a HTML page and a stateless local bean so let's get on with it.

Service interface and ServiceBean implementation

package com.aplaline.example.ejb;

import javax.ejb.Local;

@Local
public interface Service {
	String action();
}
Nothing fancy here - let's move on to the implementation:
package com.aplaline.example.ejb.impl;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.aplaline.example.ejb.Service;

@Stateless(mappedName="ServiceBean")
public class ServiceBean implements Service {
	@Override
	public String action() {
		return "Hello, world! from EJB!";
	}
}
Again... absolutely nothing fancy here - standard Hello, world! style bean. Let's see how we can configure DWR to serve the Service.action() method...

dwr.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC
    "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN"
    "http://directwebremoting.org/dwr/dwr30.dtd">

<dwr>
  <init>
    <creator id="ejb3" class="com.aplaline.dwr.Ejb3Creator" />
  </init>
  <allow>
    <create creator="ejb3" javascript="ServiceBean">
      <param name="bean" value="ear/ServiceBean/local" />
    <param name="interface" value="com.aplaline.example.ejb.Service"/>
    </create>
  </allow>
</dwr>
Now that's the meat I'm talking about! Let's get a closer look at what's in there:

The creator


The creator class originally coming from DWR is best suited for other J2EE containers but it has a huge issue with JBoss so we're implementing our own, JBoss-friendly one:
package com.aplaline.dwr;

import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.directwebremoting.create.AbstractCreator;
import org.directwebremoting.extend.Creator;
import org.directwebremoting.util.LocalUtil;
import org.directwebremoting.util.Messages;

public class Ejb3Creator extends AbstractCreator implements Creator {
  private String bean = "";
  private String interfaceClass = "";
  
  public void setBean(String bean) {
    this.bean = bean;
  }

  public void setInterface(String interfaceClass) {
    this.interfaceClass = interfaceClass;
  }

  @Override
  public Class getType() {
    try {
      return LocalUtil.classForName(interfaceClass);
    } catch (ClassNotFoundException ex) {
      throw new IllegalArgumentException(
          Messages.getString("Creator.BeanClassNotFound", interfaceClass)
      );
    }
  }

  public Object getInstance() throws InstantiationException {
    Context jndi = null;

    try {
      Properties props = new Properties();
      props.load(getClass().getResourceAsStream("/jndi.properties"));
      jndi = new InitialContext(props);
      return jndi.lookup(bean);
    } catch (Exception ex) {
      throw new InstantiationException(bean + " not bound:" + ex.getMessage());
    } finally {
      if (jndi != null) {
        try {
          jndi.close();
        } catch (NamingException ex) {
          // Ignore
        }
      }
    }
  }
}
What it does is it allows you to specify the interface class as well as full bean name as depicted in the dwr.xml example above.

The create


In here we're specifying all the bits and pieces needed for the framework later on to create JavaScript proxy and identify our bean when the time comes. This is the time to see how we can use it, shall we?

The index.html

<html>
<head>
  <title>Example</title>
  <script type="text/javascript" src="/dwr/dwr/interface/ServiceBean.js"></script>
  <script type="text/javascript" src="/dwr/dwr/engine.js"></script>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
      ServiceBean.action(function(response) {
        $("#output").append("<p>" + response + "</p>");
      });
    });
  </script>
</head>

<body>
  <h1>Example</h1>
  <div id="output"></div>
</body>
</html>
This needs a word or two of explanation. At first we're including a JavaScript proxy class that will serve as a mediator between JavaScript and the server side. Then there's the required engine.js inclusion. This includes all the bits and pieces of client side DWR. Then we're including jQuery from Google CDN because I hate to re-get the library over and over again. Then there's the most interesting part - the usage: The ServiceBean object is created by inclusion of the ServiceBean.js resource. It automatically has a action method that takes all the parameters as the server-side counterpart would (none in this example) and as the last parameter there's a callback to execute after the response is returned. Pretty simple, right?

Bottom line

If you'll ever find yourself in need to call some EJB (or Spring or Guice) managed instances from JavaScript you should seriously consider using DWR as it makes life a lot easier.

As always here is a ready-to-use example for you to check out (tested with JBoss 4.2.3).

I've been using it from within Eclipse thus the name of EAR is "ear" (and thus the JNDI name of the EJB starts with "ear/"). If you run it from command line please update the name accordingly before use!

Have fun!