Tuesday, March 29, 2011

Ext JS/Core and formatting date for Grails backend - reloaded

Here's the ultimate solution for modern browsers (works in FireFox and Chrome, there's a fix for IE):
Ext.util.JSON.encodeDate = function(o) { return JSON.stringify(o); }
I feel this needs some explanation :D So here it is:

The JSON object in modern browsers is a serializer/deserializer for JSON format. It uses all the necessary stuff (like the UTC version of date methods and adds the "Z" at the end denoting that this in fact is a Zulu time).

What about Internet Explorer? Well... There's this "fix" for this browser called json2.js. You can download it at https://github.com/douglascrockford/JSON-js/raw/master/json2.js.

The beauty of this solution however lies in the fact that it's an extremely fast solution because the browser's manufacturers are in fact able to provide an optimized version of the stringify and parse methods!

Ext core, Grails and formating dates

In my previous post I've show how to provide the Grails date JSON deserializer with proper date format from Ext JS. This time we're going to look at the same problem but with a solution that also works for Ext-Core:
Ext.util.JSON.encodeDate = function(o) {
function pad(n) {
return n < 10 ? "0" + n : n;
return '"' +
o.getUTCFullYear() + '-' +
pad(o.getUTCMonth() + 1) + '-' +
pad(o.getUTCDate()) + 'T' +
pad(o.getUTCHours()) + ':' +
pad(o.getUTCMinutes()) + ':' +
pad(o.getUTCSeconds()) + 'Z"';

This function performs much better and uses methods exposed by JavaScript's Date object instead of custom Ext JS date operations. I'd suggest this function instead of the previous one for both Ext-Core and Ext JS.

ExtJS, Grails and dates

Recently I've been made aware of a problem with interoperability between ExtJS and Grails in regards to date serialization. Here's the deal:

1. Grails expects the date to be UTC
2. Grails expects the date to end with a 'Z' (denoting that it actually is UTC)
3. ExtJS by default when parsing date thinks just concatenates the year, month, day, hour, minutes and seconds and does no other processing.

To change this behavior and make it work across different time zones right out of the box simply provide the following implementation of Ext.util.JSON.encodeDate:
Ext.util.JSON.encodeDate = function(d) {
return d
.add(Date.MINUTE, d.getTimezoneOffset())

That's it when it comes to passing dates from client to server. More on serializing date on the server next time!

Friday, March 25, 2011

Ext JS licensing - BE EXTRA CAREFUL!

It looks like the licensing terms for Ext JS library (as stated in an email conversation with Ted Driscoll) are for developers and for the once you bought is only. There would be nothing unusual about this but you have to understand that if a developer leaves the company then he TAKES THIS LICENSE WITH HIM and in best case scenario you're around $329 lighter if you hire a new developer.

Here's the conversation I've had with the said VP:


I'd like to buy 2 ExtJS licenses for developers in my team. There is however a
question of what will happen if a developer leaves the team and someone new is
hired? Will the license stay with the team or with it move away with the developer?

Ted Driscoll

The license is assigned to a specific user, so you can not move them.  
they are not floating. Hope this helps


Does this mean that when a developer leaves the company he leaves with the

Ted Driscoll

No,  but no one else can use that license.  Now having said that, if you ask
once, we will allow it, but if this happens more then one ,then we will not.
Our licenses is are per named developer
Like I said - you need to know what you're getting into. Ext JS is a fantastic library but the licensing terms are just cruel for companies willing to make software with it. Especially in today's world where developers are changing jobs often which is not only normal but also desired to attain high technical skills.

Wednesday, March 16, 2011

OOP and OOA - the new age

How come programmers have advanced so far in the evolution that the architects that lead the overall design have been left so far behind? How come that they teach and preach the same stuff their grandpa would (if he'd be still alive)?

It might seem like a strong opinion to you. Tough one if it does. You might be one of the architects that I mentioned above.

So what's the deal?

Let's examine two of the many OOP techniques at our disposal: Inheritance and Composition.

Inheritance (quoted after Wikipedia):

"In object-oriented programming (OOP), inheritance is a way to compartmentalize and reuse code by creating collections of attributes and behaviors called objects which can be based on previously created objects. In classical inheritance where objects are defined by classes, classes can inherit other classes. [...]
The inheritance concept was invented in 1967 for Simula."

Composition (again - from wikipedia):

"In computer science, object composition (not to be confused with function composition) is a way to combine simple objects or data types into more complex ones. Compositions are a critical building block of many basic data structures, including the tagged union, the linked list, and the binary tree, as well as the object used in object-oriented programming.
Composited (composed) objects are often referred to as having a "has a" relationship."

So it's dead simple, right? Son is his father's child but a car has wheels and eingine, right?

So please anyone tell me why the F so many enterprise-grade systems are created in a monolithic way? For haven's sake the 80's are gone, it's the year 2011!.

And don't you go about telling me that the technology isn't there yet! Oh it's there. In fact it's been there for a couple of years now. Starting with the first servlet containers!

So you'll say that creating a system that shares common security configuration (and thus uses some sort of single-sign-on feature) is not easy? Wake up, dude! It's been ready for ages!

So maybe it's the build time that's causing you to lean towards a monolithic design? Goddamn it! Is it really faster to build and deploy a 200MB War file than to build just one single part of it and dynamically restart the context?

Ok - I get it. You still need to cover your part of the deal, right?. If everything would be so dead simple you'd not be needed at all and that'd mean that you'd be without work. So who the hell would control what parts would need to emerge for the whole system to work??? Well, we (programmers) would't have to finally do your job.

All and all my point is: keep it simple and small.

PS. I hope you did get the irony :D

Tuesday, March 15, 2011

4.0 l/100km in Skoda Fabia Combi TDi

Today we're not talking about computers. Well, maybe just a little. But not in developer's kind of way but more like a consumer. You know? The kind of person that actually buys the stuff you created :)

So it all started on a gas station as I needed to pump some gas into my car's tank as I was running dangerously near the big far E letter. With 5.09 PLN a liter it was just just crazy so I decided to get only as little as I need to get home plus some extra in case of trouble. My car usually takes around 5l/100km, this is a 125-ish kilometer distance so I tanked for 50.03 PLN and was on my way home from work.

The traffic was as it is usually around 5pm in the slowest town in Poland. So it took me around 15 minutes to get through the worst 2km. What I noticed was an unusually low usage (around 7.9l/100km) on my on-board computer. I mean for such traffic conditions with and a cold diesel engine. This was the moment I decided to see how low can I go on the gas usage.

This time I drove precisely according to rules. 50km/h in town (or 40 when the signs said so), 90km/h outside of towns. By the time I reached 90th kilometer my usage dropped to 4.1 l/100km so it was already my personal record.

After going through small cities I finally arrive at a point where I joined the A4. Normally I'm a "pedal to the metal" kind of guy but not this time. I followed a truck going about 90 km/h, didn't accelerate much.. and after the 100th kilometer I've reached the usage of 4.0 liter per 100km.

For the rest of the road I've tried as hard as I could to keep my foot light (which is kind of freaky when you're one of the slowest cars on the highway and normally it's more/less the opposite).

Here's the route in details:

A - My workplace
B - Gas station (damn you BP! 5.09PLN for a liter of diesel gasoline!)
C - Complete stop due to traffic lights
D - There's actually a roundabout and I took a wrong turn
E - Here I've made a U-turn after driving this God forsaken "road"
F - Just before the traffic lights I've noticed a 3.9 l/100km usage!
G - My joy didn't last long (damn traffic lights...)

So it is possible. I've done it. 4.0l, it's a 124km drive (according to the readings of the on-board computer) so it worth 25.25 PLN. By comparison taking a train costs arount 35PLN and takes 4 hours 30 minutes (if you're lucky).

Did anyone had similar experiences? Please share!

Sunday, March 13, 2011

Ext JS, RowExpander and Ajax

Ext JS contains almost everything a body needs. If there's some functionality that's missing there's always the option to create plugins to extend the core functionality.

For example there's a RowExpander plugin that allows you to create details for rows in a grid, which is very neat. The only problem with that is that it needs the details loaded with the parent row which (if you need to perform more exhaustive queries) is bad.

So after googling a bit I've came up with the idea of extending the original plugin so that it allows for loading content from an external source.

The original idea is taken from this old post.

The idea is simple: return a placeholder instead of template, load the content using an Ajax call and store the retrieved content in the placeholder once it arrives.

I needed this plugin to be able to process the content using template as well so there's the "mode" config option which can be set to 'html' (as-returned-by-server) or 'tpl' (which means that the tpl template will receive an object with 2 fields: parent - with the parent record data, and details - with the parsed object or list returned by server).

The example is here

And finally the sources can be downloaded from my Git repository here.

Monday, March 7, 2011

Grails, Tomcat and additional contexts

I needed to create a modular application today. It was nice and easy up to the point where I needed to make some ajax calls and due to the same-origin principle it was all failing miserably in development. In production, since both apps are on the same tomcat instance everything works just fine.

To be able to add more contexts to the very lonely tomcat instance fired by Grails create a _Events.groovy file in your scripts folder with content like this
eventConfigureTomcat = {tomcat ->
def ctxName = "secondary"
def ctx = tomcat.addContext("/${ctxName}", System.getProperty("java.io.tmpdir"))
def servlet = tomcat.addServlet(ctx, "my-servlet", new MyServlet())
servlet.addInitParameter("some-param", "some-value")
ctx.addServletMapping("/*", "my-servlet")

Here's some explanation:

1. This will bring up a secondary context called "secondary" (so you can access it under http://localhost:8080/secondary)
2. It will bind to all requests below this url to MyServlet instance

Using the HttpProxyServlet I'm now able to have the secondary applications available on the same tomcat instance:
import com.jsos.httpproxy.HttpProxyServlet

def map(tomcat, ctxName, port) {
def ctx = tomcat.addContext("/${ctxName}", System.getProperty("java.io.tmpdir"))
def servlet = tomcat.addServlet(ctx, "proxy", new HttpProxyServlet())
servlet.addInitParameter("host", "http://localhost:${port}/")
servlet.addInitParameter("uri", "/")
ctx.addServletMapping("/*", "proxy")

eventConfigureTomcat = {tomcat ->
println "Configuring tomcat"
map(tomcat, "first", 8081)
map(tomcat, "second", 8082)

Hope this will give you more flexibility doing stuff with Grails!

Sunday, March 6, 2011

Grails, Ext JS and desktop-like applications

I've just finished work on the Ext JS resource integration for Grails. This plugin's main purpose is to start coding Ext JS applications in no time.

An added bonus with this plugin is the distribution of the ux-all package (it comes in the package with Ext JS) as well as a slightly modified version one of the examples - the Desktop application.

So what I did to the Desktop example was to externalize the creation of desktop icons (it was really stupid to code all the icons directly in HTML) as well as the inclusion of ScriptLoader utility that allows to load additional scripts on demand.

If you'd like to give it a try there's a load of information on the plugin's page on how to create a desktop-like application in under 5 minutes :)

And if you'd like to get the sources here's the git repo with them: http://dev.aplaline.com/git/grails-extjs.git

The sources also contain some documentation (which is basically the one from plugin's page but dissected into smaller chunks for easier navigation). To generate the final version run grails doc in the main plugin folder and in a matter of seconds target/docs you'll find a ready to browse version of the documentation. I might put it online some day :)

Ext.Direct and Grails

I just started a new Grails plugin that will (in theory) allow Grails service's method to be called using Ext.Direct JavaScript client. Obviously I've looked at existing libraries to do this (the directjngine and extdirect4java) but as far as my taste goes they are not groovy enough. My thinking is that Groovy allows for typeless declarations for parameters and JavaScript does the same. So additional metadata (like annotations in case of the 2 engines mentioned above) should not be needed. All is there in the code already.

We'll see where this will take me :)

You can follow my endeavors on GitHub