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!

Wednesday, August 31, 2011

New guy in town: knockout.js

Today we're going to take client-side JavaScript to a whole new level with the MVVM pattern using knockout.js.

The "why"


Imagine you're writing an application using, let's say, WPF or Silverlight. What's nice is that you have a clean separation of concerns between what's being displayed in terms of the layout (which is in fact the first V in MVVM) and some object backing up that view (which is the VM in MVVM in this case). This allows the application to be extensible and well structured.
Granted you can make a mess everywhere and MVVM architecture is no exception. You still have to use your brain while coding :)
Up until recently there has been no framework giving you the opportunity to have that kind of clear separation in JavaScript. Granted there have been tools like ExtJS and jQuery to help you out with modern UI elements like calendars and grids as well as low-level operations on DOM and events but there has been nothing so far that'd help you out write in a clear MVVM declarative style. Now there is!

The "what"


That's quite simple: the mini framework is called knockout.js and implements the MVVM pattern in pure JavaScript and DOM (not necessarily HTML but that'll work for DOM creation as well).

The "how"


Well, here's the good part, which will be extremely easy:

<html>

<head>
<title>Example</title>
<script 
type="text/javascript" 
src="https://github.com/downloads/SteveSanderson/knockout/knockout-1.2.1.js">
</script>
<script 
type="text/javascript" 
src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
var viewModel = {
data: ko.observable("Hello, world!")
};

ko.applyBindings(viewModel);
});
</script>
</head>

<body>
<p>The current value of data is <span data-bind="text: data"></span></p>
<p><input type="text" data-bind="value: data"/></p>
</body>

</html>
See how there's no "Apply changes" button? This is because once you've entered the text into the input box it'll be automatically transferred to the viewModel object and since that's an observable it'll notify all subscribers about the fact that the value has changed and the text on the page gets updated automagically.

Going fancy


I'd like to see some fancy stuff in here like responding to button events and the like. Let's see how we can do that with KO:

<html>

<head>
<title>Example</title>
<script 
type="text/javascript" 
src="https://github.com/downloads/SteveSanderson/knockout/knockout-1.2.1.js">
</script>
<script 
type="text/javascript" 
src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
var viewModel = {
data: ko.observable("Hello, world!"),
show: function() {
alert("Current value is: " + viewModel.data());
}
};

ko.applyBindings(viewModel);
});
</script>
</head>

<body>
<p>The current value of data is <span data-bind="text: data"></span></p>
<p><input type="text" data-bind="value: data"/></p>
<p><button data-bind="click: show">Click me</button>
</body>

</html>
Again, the same page but with 2 additions:
1. A callback function called show as part of the viewModel
2. Declarative binding of the above function to a button using the last data-bind. Cute, isn't it?

I know that I'll put it to some good use in my next project. Just for the heck of it :) I like the idea that it is completely cross-platform and yet so incredibly easy to use!

Tuesday, August 30, 2011

JSF 2.0 - Is it really better?

I know most of you will hate me for the post I'm writing but I have no choice. I really need to stigmatize the framework and make clear to anybody still using it that they have been lost in the woods. Literally...

Like you (as the reader of my blog) already know I hate JSF. I hate it so much that I've dedicated an entire blog and site to bitch about what a pain in the ass it is to use. Being the enlightened man I am from time to time I like to come back to stuff I hate to make sure they didn't do anything stupid like making the framework usable or so. This time was no different.

So I did it. I've installed NetBeans (I usually use the Far Manager's build-in editor but for this exercise I've decided to go crazy a bit and use the full-blown IDE supported by JSF's creators). I've followed the standard File -> New procedure, selected some JSF JPA CRUD example (because I couldn't find anything simple on the net) and started reviewing the app.

First thing that hit me was the really cruel style of the web UI the application presents. In one word "HORRIBLE". Not that it ain't usable - God forbid - but plain "usable" these days just will not cut it. So the GUI is butt ugly - how about the code?

Now that's the place I like JSF most for: the code was just exemplary bloated :D Let me give you some bottom line figures:

1. It's a pure CRUD application. Absolutely nothing fancy. No Ajax or the like cool features whatsoever.
2. It's an application that manages 7 entities (customer, discount code, manufacturer, micro market, product code, product and purchase order).
3. Everything that was generated is 706068 bytes in 72 files!!!

Now compare this to, let's say, Rails, Grails or Sinatra + Data Mapper is about 8 times bigger. I know it is an enterprise sort of thing and that it's not meant for mare mortals. It's the enterprise kind of solution that you'd use at work and not for fun.

Anyways, JSF still sucks, big time. Lot's of hand-written XML, tons of Java code to implement pretty much every aspect of the application (with parts of it having cyclomatic code complexity at the level of 20+). That's just a no-go for new projects that need to deliver solutions on time, on budget and in scope.

One last thing: For crying out loud the web is stateless! Why would anyone force a solution that inherently introduces state which in turn means no scaling possibilities and stupid ideas like "page life cycle" and "control binding"? Why would you ever want to fear JavaScript programming when there are layers of abstraction like Ext JS or jQuery?

I wonder if the MyFaces implementation still differs from the reference one in the way that component libraries will work on one and not the other. I didn't check it out myself - I'm not that brave...

The conclusion is that if you're still doing JSF these days just drop it. Now. It's horrible!

Thursday, August 25, 2011

The Process

I've been working this past few years for a company that utilized Rational tools for issue tracking and source code versioning. Long story short it was a nightmare to use ClearCase and ClearQuest with its stone age web interface was more than annoying but it was to some extent usable.

Nowadays the same workflow is doable using opensource tools like Git and GitHub for anyone. Here's how the process works:

- request a change to the system
- do the changes
- integrate them to the so called main line

Using GitHub it's dead simple:

- file an issue
- clone the repository, do some changes, check them in
- put out a pull request for the maintainer to integrate your changes

All that takes some 2-3 minutes if you know what you're doing and if the test suite you're dealing with is fast enough. Piece of cake.

Now if you'd like know how it looks like using Rational tools (and I mean the good stuff, fully integrated) take a look at the following screen cast.

I hope ClearCase will soon be seen for what it really is: a performance and evolution blocker.