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!

Wednesday, September 21, 2011

Using JRebel from pure Maven in a web application

Hi there folks!

I'm sure you've read every bit and piece about how to bend Maven to do your bidding. This time I'm most probably going to duplicate a lot of stuff found on other sites but I'm simply sick and tired of looking it up every single time I need it. We're going to configure a Maven web application project to run under Jetty (mvn jetty:run) with JRebel to do the reloading. So let's get started!

Installing Maven and JRebel

That one is a no brainer but for the sake of completeness I list this particular step here as well.

The pom.xml

The pom.xml file we're going to use looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>war</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>Example Web application</name>

  <properties>
    <!-- stop stuppid Maven message about build being platform-dependant -->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <build>
    <plugins>
      <!-- make sure we're using Java 1.6 and not some stone age version -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
      <!-- enable jetty:run mojo -->
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
        <configuration>
          <scanIntervalSeconds>0</scanIntervalSeconds>
        </configuration>
      </plugin>
      <!-- enable generation of jrebel.xml - needed for the agent -->
      <plugin>
        <groupId>org.zeroturnaround</groupId>
        <artifactId>jrebel-maven-plugin</artifactId>
        <executions>
          <execution>
            <id>generate-rebel-xml</id>
            <phase>process-resources</phase>
            <goals>
              <goal>generate</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

Running Maven with JRebel

You need to specify the javaagent as JRebel in order for the class-reloading to work. You do that by extending the environment variable MAVEN_OPTS with the following:
set MAVEN_OPTS=-javaagent:C:\progra~1\ZeroTurnaround\JRebel\jrebel.jar %MAVEN_OPTS%
With that in place run mvn jetty:run or mvn tomcat:run and you're all set!

Doing reloading

Please bare in mind that Maven is not Eclipse! When you save a file it doesn't automatically recompile it so in order for the modified class to be reloaded you need to recompile the project using mvn compile!

Well that pretty much summarizes it. It's not very difficult to setup as you see here but there are steps that are not described all in one place so here it is for your entertainment :)

Have fun!

Sunday, September 18, 2011

Java 6 has a web server inside!

The what

I'm into miniaturization - anyone who knows me also knows as much. Probably because I'm not very tall for today's standards but mostly due to the sole nature of small things: they are easy to figure out. For example getting to understand every bit and piece of the whole car (whatever brand) is impossible. In many cases no one would even allow you to go that far. But having a deep understanding how manual shift gear box works shouldn't be a problem for moderately intelligent person... The exact same principle adheres to software development as far as I am concerned. I like small parts I can grasp in short amount of time and have it used right after the learning process knowing what the hell I'm doing. You might think about it in terms of components of a desktop application, a JavaScript library for dynamic web pages or (as I've found out today) in terms of a small set of classes that do exactly what they are supposed to do and you can have them do their thing in a matter of minutes. I'm obviously (as the title suggests) talking here about the embedded web server found in the com.sun.net.httpserver package.

The how

Besides being fixated on miniaturization I'm also a Groovy freak as I thing this is the best language for JVM ever created and there's nobody to convince me otherwise :D For that very reason the following example showing a miniature web application with embedded web server is a Groovy script:
import com.sun.net.httpserver.*

class ExampleHandler implements HttpHandler {
	void handle(HttpExchange exchange) throws IOException {
		def response = "Hello, world!"

		exchange.sendResponseHeaders(200, response.length());
		def outout = exchange.responseBody
		outout.write(response.bytes);
		outout.close();
	}
}

public class ExampleAuthenticator extends BasicAuthenticator {
	static users = [ "john": "john123" ]
 
	public ExampleAuthenticator(String realm) {
		super(realm);
	}

	@Override
	public boolean checkCredentials(String username, String password) {
		return users[username] == password;
	}
}

def server = HttpServer.create(new InetSocketAddress(8000), 0);
def context = server.createContext("/example", new ExampleHandler());
context.authenticator = new ExampleAuthenticator("Example application")
server.executor = null
server.start();
Let's start from the beginning...

The ExampleHandler class

This particular class is responsible for generating all the output sent later on to the server. As you can see it's a very minimalistic thing here, even to the point where the body needs to know how big it actually is. The line Exchange.sendResponseHeaders(...) shows that. The rest is pretty self explanatory so I'm not going to drill into it.

The ExampleAuthenticator class

This class provides basic authentication for our small application. It's so damn easy anyone will understand it right away but for the sake of clarity here's the bottom line:
  • Every credential is stored in the static users=[:] map

The meat

Now we have finally come to the good part! The actual use of HttpServer. Here you see how the server is created using a factory method (HttpServer.create) that takes an InetSocketAddress and some other argument I didn't drill down to just yet and gives you back an HttpServer instance ready to work. That instance does pretty much nothing so far other than a response 404 for everything you ask. To change that we create a new application context (very similar to the one found in a Servlet container) and register it under a specific path on that server. In the next line we tell the context that it is guarded by basic authentication - that's my favorite :) - and we're almost all set. The last thing is to (for whatever reason) assign an empty executor that in turn is supposed to have a side effect in the sense that a default executor will be assigned instead. That's weird...

The outcome

In 32 lines we've created a dynamic web application with authentication - ready to conquer the world! That's maybe a lot more than Sinatra or Spark but still - it's something worth knowing about. If you'd like you can utilize it directly from Java and it is still not a lot more code than what's seen here!

Have fun!

Tuesday, September 13, 2011

How I wrote my own version control system

This is what happens when people have too much spare time traveling from home to work and back 6 hours a day... They create useless software that allows them to pass the time.

The idea

The idea was to create something that'll be astonishing, maybe not new but great in functionality and to do it in Groovy. I thought what the hell - why not write your own version control system :) Let's call it pico

The credits

The piece is 100% cloned in idea (and most of the solution as well) from The All Mighty And Only True Version control system - meaning Git.

What's it doing?

For now it is really simple: it can commit with a message (the user interface is sooooo cruel - need to work on it a bit), dump a sophisticated log and checkout the latest version. It's faaaaaaar from being complete and most probably it'll never get where Git is today but hey - that's what passing time means :D

But....

It does what it does and is written in Groovy! Granted that I can do better but trust me coming up with a working solution like that in less than 3 hours on a train was my point here - not the beautiful code :) The latter one is due some time in the future to fill the time...

The code

You can find the code as well as a batch file (yes, I am a Windows freak) here.

Have fun!

Thursday, September 8, 2011

Grails, multi-tenant plugin and a bag of small issues

If you'll ever need a multi-tenant solution and you're lucky enough to use Grails going with the multi-tenant-core plugin is definitely the way to go. It's pretty easy to use in the "multiTenant" mode but some strange issues come up when trying yo use the "singleTenant" mode. In this installment I'm going to walk you through a solution that'll allow you to understand how things are and what you should avoid.

The debug solution

To make our "explorer" live easier we're going to provide a custom tenant resolver so that we'll be able to specify a query string like ?tid=1 to select the tenant with id = 1.
package org.example

import javax.servlet.http.HttpServletRequest
import grails.plugin.multitenant.core.TenantResolver

class TestTenantResolver implements TenantResolver {
    Integer getTenantFromRequest(HttpServletRequest request) {
        def tid = request.queryString =~ /tid=(\d+)/
        return tid ? Integer.parseInt(tid[0][1]) : 0
    }
}
To use it just register a bean with name tenantResolver in resources.groovy like
tenantResolver(org.example.TestTenantResolver)
this and you're all set.

The data sources

Although the documentation will tell you that in the tenant configuration DSL you can specify JDBC URLs directly it is unfortunately not true. You need your JDBC datasources registered in JNDI for the multi-tenant plugin to pick them up. It's done in Config.groovy like this:
grails.naming.entries = [
    "jdbc/foo": [
        type: "javax.sql.DataSource", 
        driverClassName: "org.hsqldb.jdbcDriver",
        url: "jdbc:hsqldb:file:target/db-dev-tid-1;shutdown=true",
        username: "sa",
        password: "",
        maxActive: "8",
        maxIdle: "4"
    ],
    "jdbc/bar": [
        type: "javax.sql.DataSource", 
        driverClassName: "org.hsqldb.jdbcDriver",
        url: "jdbc:hsqldb:file:target/db-dev-tid-2;shutdown=true",
        username: "sa",
        password: "",
        maxActive: "8",
        maxIdle: "4"
    ]
]
And then you need to tell the plugin about your datasources:
tenant {
    mode = "singleTenant"
    dataSourceTenantMap {
        t1 = "java:comp/env/jdbc/foo" 
        t2 = "java:comp/env/jdbc/bar" 
    }
}

Catch No. 0 (zero)

Be warned that the tenant 0 (zero) has a special meaning that's not mentioned anywhere in the docs. It means "use the connection returned originally by TransactionAwareDataSourceProxy". This means that tenant with id 0 is off limits for you. Don't ever use it!!!

Summary

Other than the 2 small issues the plugin is really fun to work with. Good job guys!