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!

Wednesday, September 28, 2011

What the hell is wrong with collections API in Java?!

Today is the day when steam came out of my ears and I started screaming "WTF?!?!". So what's wrong? Let me explain...

The good part

I came to pure Java from Groovy. I never liked Java as a language in particular (I'd even go as far as "I hated it with a passion") but life is life and I've had to put my hands into the dirty world of legacy Java code once again. Being the Groovy fan for quite some time now tough me that functional programming style is something that makes your life easier and the code itself a lot more readable. That's especially true in regards to collections!

I don't want to bring up obvious examples like sorting a collection using spaceship operator or something along those lines. That's been done to death. Instead I'm going to tell you a story...

The story so far...

Back in the days there have been collections and a handful of utilities to back up the bare collection objects (java.util.Collections). At some point people saw that what the creators of Java the runtime library gave them to play around was not enough so they invented commons-collections. And life was good again because we could do things easily that were cumbersome before. That was in the pre-1.5 days so no generics were involved as you might imagine. That in turn forced the developer to do idiotic type casts from Object to the respective type when implementing for example a Transformer.
After a while Java the language 1.5 came to existence so people sat there and wondered how we can make the best out of it. This is how commons-generic came to be: The same set of utilities but with generic parameters so you can avoid doing silly casts. That must have been a brilliant idea, you might wonder... But as it turns out the compatibility is virtually non-existent so you can stick it up a$$ since everyone else is using the old commons-collection anyways...
If that wouldn't ring any bells yet not so long ago Google came up with yet another professional and good looking collections library, the google-collections project later on included into google-guava. Yet again the same stuff happened: separate predicate definitions, mapping functions - you name it!

Groovy the savier

I know you're going to say that Groovy is a dynamic language and I should back off of Java and not compare apples and oranges together. But then wouldn't it be at least sane to allow some classes/interfaces to be extended in some way? Like they do it in C# or VB using extension methods... Oh and btw. if you're saying that they will be in version 8 I rush to explain that C# had them from 3.0 which is not so far away from Java 1.5 as far as I can remember...
So back to Groovy... If you want to transform some list of objects into another list of objects you have the all mighty collect method that does exactly what you need. If you want to extract just a single property from all instances in collection you just type for example people.firstName and that's it. It's really simple...

But there we are... in Java

If you'd like to make use of your code in all the fancy collection utilities hyper super duper tools you'll have to create your own version of the predicates/mapping functions (to be on the safe side, of course) and then create tons of adapters just to satisfy the compiler and the ever growing egos of collection utilities libraries creators.

Have fun!

Friday, September 23, 2011

CORS filter for Java applications

Hi there, in today's installment we're going to allow Ajax calls from other domains to be answered and accepted by browsers.

The what

This thing (completely forgotten by many) is called Cross Origin Resource Sharing and works with standard Ajax requests your browser can send. You can read about it in depth on Wikipedia or on the http://enable-cors.org/ site.

The how

Let's get to the meat - shall we? On the http://enable-cors.org/ site there are many recipes for all kind of servers and they respective configuration but what if you'd like to enable CORS just for a part of your application? If you're lucky enough and you're coding your application in Java then there is a standard mechanism to do just that! It's called filters.
Here's the most simple way of implementing CORS response headers:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class CORSFilter implements Filter {

	public CORSFilter() { }

	public void init(FilterConfig fConfig) throws ServletException { }

	public void destroy() {	}

	public void doFilter(
		ServletRequest request, ServletResponse response, 
		FilterChain chain) throws IOException, ServletException {

		((HttpServletResponse)response).addHeader(
			"Access-Control-Allow-Origin", "*"
		);
		chain.doFilter(request, response);
	}
}
As you can see here all we're doing is adding the Access-Control-Allow-Origin header so that the browser can accept the response sent by server.

You can use this filter as follows in your web.xml:
<web-app>
	<filter>
		<filter-name>CORSFilter</filter-name>
		<filter-class>CORSFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>CORSFilter</filter-name>
		<url-pattern>/api/*</url-pattern>
	</filter-mapping>
</web-app>

Have fun!