Wednesday, March 31, 2010


Recently, found amazing Swing layout manager called MigLayout.

Compare this GroupLayout:

    GroupLayout layout = new GroupLayout(infoPanel);
    GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
    hGroup.addGroup(layout.createParallelGroup().addGroup(layout.createSequentialGroup().addComponent(typeUser).addComponent(typePlaylist).addComponent(typeFavorites)).addComponent(formats).addComponent(id).addComponent(result, GroupLayout.DEFAULT_SIZE, 400, GroupLayout.DEFAULT_SIZE));
    GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();
    vGroup.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(resultLabel).addComponent(result, GroupLayout.DEFAULT_SIZE, 200, GroupLayout.DEFAULT_SIZE).addComponent(copyButton));

to this MigLayout:

    JPanel infoPanel = new JPanel(new MigLayout("", "[][grow][]", "[][][][grow]"));
    infoPanel.add(typeLabel, "");
    infoPanel.add(typeUser, "split 3");
    infoPanel.add(typePlaylist, "");
    infoPanel.add(typeFavorites, "wrap");
    infoPanel.add(formatLabel, "");
    infoPanel.add(formats, "wrap");
    infoPanel.add(idLabel, "");
    infoPanel.add(id, "growx, width 30::");
    infoPanel.add(generateButton, "wrap");
    infoPanel.add(resultLabel, "top");
    infoPanel.add(result, "grow, width 30:300:, height 10:100:");
    infoPanel.add(copyButton, "top");

Both pieces of code layouts form the same way, but code for GroupLayout looks squared compared to MigLayout. And I was thinking GroupLayout is good!

It is absolutely amazing how more undestandable it is compared to any other layout and how powerfull it is. I have created my form in 5 minutes after reading "Quick Start" guide. This MigLayout is also available for SWT and JavaFX, so maybe JavaFX is not that bad after all (except for textareas).


For new project, I need to create desktop UI. Of course there is good old Swing, but it is good known for his flaws and it is always interesting to pick something new and sexy. JavaFX got some buzz lately, so I decided to try it.

There are several installation of JavaFX, I decided to go with simple SDK. Installation was ok, I had to update my JDK to 6u18. From development process perspective I was not expecting anything fancy, nice Ant task to compile files was completely sufficient. Compiled code runs simply by Java runtime, no special tools needed - just bunch of new libs. So there is little overhead over any classic Swing application, that can run on plain JDK.

JavaFX has it's own language, which looks like some mix between JSON (visually) and HTML (idea), plus it can hold scripts. Language is quite ok, but in my opinion desktop requires more separation between layout, styles and code like in web development, but here again everything is mixed like in Swing. But anyway, language is quite ellegant and is easily understood.

Stage {
    title: "Test"
    scene: Scene {
        width: 300
        height: 250
        content: [
          VBox {translateX: 10 translateY: 10 spacing: 20
                content: [
                     HBox {spacing: 5
                       content: [
                         Label {text: "Field:"}
                         Button {text: "Button1" strong: true }
                         Button {text: "Button2" strong: true }

Minus is that language is not supported by my Intellij, but there are plugins for Eclipse and NetBeans.

But what totally disapointed me was that it is looks very raw and not ready for production use. For example, there is no textarea (TEXTAREA!!!),  there are only basic layouts like grid and horizontal/vertical boxes. In Java 6 there is already GroupLayout, it even looks the same way as JavaFX, but still for some reason it is not part of it. There is general feeling that it is more like some fancy toy, but not usefull tool to do things. What kind of form can one build with grid layout?

There is one interesting concept though. Which maybe even future of layout managers - it is called binding. I have not seen anything like it before and to me it seems really interesting. It is possible to bind one parameter to some variable or variable expression, and when this bound variable changes, initial parameter is updated. So for example, you can bind start of textfields to maximum value of labels and this way to have nicely aligned form.

Anyway, even if there are some cool and promising features, I needed textarea and some normal layout for forms, so I decided to stick with Swing just for a while more.

Maybe I'll have more luck with Griffon.

There was article on JavaLobby with link to another article about upcomming features in JavaFX 1.3. And it already looks a little bit better with Textarea and CSS. So I'll wait for next version.

Full article at

Tuesday, March 30, 2010


For one new project I have had to choose new build tool. I know Maven and Ant for long time already and heard about Gradle here and there. So I have decided first to check these tools, and only look for something else if they will not be good for me.

My project is quite small and I was not going to configure it a lot, so some all-in-one tool would be great, however some customization would be still nice.

So Ant is good that it is extremely popular and robust and can be extended and customized quite easily. Big minus for me is that it does not have build in dependency manager, so I have to download and additionally configure Ivy. Also, I have to configure absolutely everything, there is no defaults like in Maven.

Maven is good, because it has these defaults, like compile, test and build. It has also dependency manager, which is great. Unfortunately, it is not easily customizable, and I need customization. For example, for Java Web Start project I need to sign all dependency jars (in Maven there is only plugin to sign build jar), I also need to upload automaticaly my jars and other files to Google Code.

So here comes Gradle. In short it combines good things from both Maven and Ant: includes dependency management (via Ivy, but with native Gradle integration) and has predefined tasks like Maven; all extension in one same build file like with Ant and natively can call Ant tasks - so you don't have to throw them away or rewrite everything.

Plus, there is also one (and not so little) bonus: no XML, all configuration is in Groovy, which is both: sexier and easier. There is only one minus I can see so far - it is quite large, about 20M, probably because it packages Groovy inside it, but anyway it is not show stopper for me.

Few examples:

Dependency definitions:

dependencies {
    compile group: 'org.eclipse.jetty', name: 'jetty-server', version: '7.0.1.v20091125'
    compile group: 'org.eclipse.jetty', name: 'jetty-servlet', version: '7.0.1.v20091125'
    compile group: 'org.eclipse.jetty', name: 'jetty-util', version: '7.0.1.v20091125'
    compile group: 'org.eclipse.jetty', name: 'jetty-http', version: '7.0.1.v20091125'
    compile group: 'javax.servlet', name: 'servlet-api', version: '2.5'
    testCompile group: 'junit', name: 'junit', version: '4.+'

Dependencies are downloaded from Maven repository by default.

This is simple task that cleans and creates folder for libs and signs all runtime dependencies:

task copyAndSign() << {
    for(file in configurations.runtime.resolve()) {
      ant.signjar(destDir: 'build/signed', jar: file, alias:"myself", keystore:"myKeystore", storepass:"123456", preservelastmodified:"true")

It uses Ant tasks to do actual job.

This task signs jar file after running JAR task, of course it will be run also after any task that depends on JAR task.

jar.doLast {
  ant.signjar(destDir: 'build/signed', jar: tasks.jar.archivePath, alias:"myself", keystore:"myKeystore", :"123456", preservelastmodified:"true")

You can also define custom Ant task from Gradle.

ant {
  taskdef( name: 'gcupload', classname: 'net.bluecow.googlecode.ant.GoogleCodeUploadTask', classpath: 'ant/ant-googlecode-0.0.2.jar' )
task uploadAll << {
  collection = files { file('build/signed/').listFiles() }
  collection.each { 
    ant.gcupload(username:gcusername, password:gcpassword, projectname:"project", 
        filename:it,, summary:"automatic", labels:"")

Tuesday, March 16, 2010

Code bubbles IDE

There is  buzz in java world about new IDE concept. Idea is that it combines contexts and helps to keep all related files and information around tasks and ideas, but not around files and classes like traditional IDE.
Generally it is the same Mylyn idea, maybe better implementation, but should be tried.
Interesting presentation anyway.

Sunday, March 14, 2010

Ajax mock

One thing missing in QUnit and other javascript frameworks that I was looking for is mocking. Mock is object that replaces some complicated system, to simplify tests.
For example, I want to test javascript that I have ajax calls.

function serverSideSum(v1, v2) {
  $.post('http://localhost/sum', {val1: v1, val2: v2}, function(data) {

Normally, to make them work I have to run server that would answer to my calls. There is a number of problems
  • It is much slower compared to normal javascript tests
  • It requires infrastructure
  • How to check that my javascript sends correct data?
  • How to validate response or be sure that server part is not broken
Other option is to replace calls to real server with artificial function calls that always returns good results.
  • It is fast
  • Runs without server
  • Can check input data
  • Server response is always as good as you need

It is very easy to create mock in javascript. You just have to redefine some function. For example in JQuery ajax calls are sent by calling $.post() and $.get()
methods. So mock can be:

$.post = function(url, data, func) {

We can check parameters too:

$.post = function(url, data, func) {
  equals(data.val1, 2);
  equals(data.val2, 2);

And complete test looks like:

test("server side 2+2=4", function() {
  $.post = function(url, data, func) {
    equals(data.val1, 2);
    equals(data.val2, 2);
  serverSideSum(2, 2);
  equals(4, $('#result').text());

Nice, but what if there are several calls to same ajax method during one function invocation?
For example, our function will also get number of calls to server:

function serverSideSum(v1, v2) {
  $.post('http://localhost/sum', {val1: v1, val2: v2}, function(data) {
  $.post('http://localhost/counter', {}, function(data) {

Finally we can update our test to something like:

test("server side 2+2=4", function() {
    [{result:4}, function(data) {equals(data.val1, 2); equals(data.val2, 2);}],
    [{count:123}, function(data) {}]
  serverSideSum(2, 2);
  equals(4, $('#result').text());
  equals(123, $('#counter').text());

Function ajaxMock has one parameter - array of objects, and every object represents one ajax call and consists of call results and function thatvalidates input parameters.
Implementation of this method can be something like this:

function ajaxMock(params) {
  ajaxCallsCounter = 0;
  ajaxCallsParams = params;
  var callback = function(url, data, func) {
  $.get = callback;
  $.post = callback;

All ajax calls are stored in memory. After ajax call, array index ajaxCallsCounter will be increased and will not be called again, so this ensures that all ajax calls are done only once and in correct order.
Additionaly, you can verify that all calls were made by comparing array index with it's length, like this:

equals(ajaxCallsCounter, ajaxCallsParams.length);

Tuesday, March 9, 2010

YouTube API issue too_many_recent_calls

I have application on Google App Engine that uses YouTube API.
Recently I got error message like:
Which started to pop-up more and more often.
I have investigated this quota issue and solved problem by adding developers key to all API requests. And it nicely resolved this issue.
My guess is that someone else from same sever started to use YouTube API, but when there is no developers key, YouTube tracks number of request by IP address or something.

Groovy and SQL

Today I needed to do some boring import into db for some predefined structure and decided to do it some new way, just to stretch brain a little bit. I decided to use Groovy, as it seems that it was made for such things.

GSQL is built-in feature in Groovy so it does not require any additional lib, but database driver lib is still needed.

Connecting to dabase is as easy as:

import groovy.sql.Sql
sql = Sql.newInstance("jdbc:oracle:thin:@########", "login", "password", "oracle.jdbc.driver.OracleDriver")

To iterate table it is only needed

    sql.eachRow("select * from get_data_from_table") {goal-> 

And you can access table fields just as parameters.

To insert new row you just need to

    def display = sql.dataSet("add_to_table") 
    display.add(id:goal.goal_id, country:it, type:'P') 

Quick and simple, just what is needed for such kind of scripts.

My only dissapointment with Groovy today was Grape. My idea was to inject it into script and download Oracle drivers automatically, but for some reasons it didn't worked out and I didn't had time to investigate and fix it. I hope to try it next time.

import groovy.sql.Sql
sql = Sql.newInstance("jdbc:oracle:thin:@########", "login", "password", "oracle.jdbc.driver.OracleDriver")
langs = ['LV', 'LT', 'EE']

def update() { 
    def display = sql.dataSet("add_to_table") 
    sql.eachRow("select * from get_data_from_table") {goal-> 
            display.add(id:goal.goal_id, country:it, type:'P') 
            display.add(id:goal.goal_id, country:it, type:'B') 


Sunday, March 7, 2010

Generics in Hibernate

Recently, I found one feature from Hibernate that I am missing. I have two identical tables that differs only by foreign keys. Looks like perfect case for generics. Like:

<class name="com.test.GenericClass<Reference>">

But it does not looks like Hibernate supports it. So finally, I had to create empty implementations for my classes. Like:

public class SpecificClass extends GenericClass<Reference>

Saturday, March 6, 2010

BDD - Behavior Driven Development

New interesting methodology that combines automatic testing and requirements specification. I love the concept for some time with Fitnesse, but here is another formalized methodology and buzzword. More about it here.

Method chaining issue

I met one interesting issue with method chaining today.
Method chaining is popular thing now, introduced by Martin Fowler and you probably seen it somewhere already, you can read about it here.
Generaly it looks like:

new HardDrive().capacity(150).external().speed(7200);

contrary to classic Java style

HardDrive hd = new HardDrive();

Today I found one funny issue with it. I got bug in this code:

parent.add(new Node()

Of course, bug is trivial and easily found with debug. But what is bad with this bug, syntax is correct, so it is not discovered by IDE and it is not easily visible. For example, compare it to old style:

Node node = new Node();

Another minor bonus is that it is also easier to debug.

JSON formatting

Sometimes it is needed to format JSON to check it's content. Intellij IDEA and Eclipse do the job pretty well, but if these are not available it is easily possible in Google Chrome. To do it:
1) Go to Control the current page menu (document icon to the left of address input) then Developer/JavaScript console.
2) Enter console.log({qwe:123}) (where {qwe:123} is just any JSON object).
3) You got nice JSON object tree as output.
There is some noise from Chrome, but it is possible to see and browse your object.
Same feature is in Firefox with Firebug plugin, even the same syntax.

UPDATED: Nice online JSON formatting tool: .

Friday, March 5, 2010

Javascript unit testing

Javascript unit test framework is just plain html file loaded in browser, which executes your javascript code in predefined order.
It is quite easy to create it from scratch, but there is a plenty of ready frameworks, that provide nice reports and allow to run different combinations of tests.
I tried QUnit and it quite ok. It is just basically several files, that you have to download - javascript and css. Then you have to create new html file where you will describe your tests. Also from this html you have to link QUnit files and javascript code that you want to test. Unless you want to put your functions in test file, you must have javascript in separate file.
So, in the end you will have something like this:

    <script src="jquery-1.3.2.js"></script>
    <script src="testrunner.js"></script>
    <script type="text/javascript" src="code.js" ></script>
    <link rel="stylesheet" href="testsuite.css" type="text/css"/>
    <script type="text/javascript">

    <ol id="tests"></ol>
    <div id="main"></div>

Where code.js is your javascript code to test.
<ol id="tests"></ol> and <div id="main"></div> is where QUnit puts it's stats.
Now you can start to write tests.
For example, our code.js has something like:

function sum(v1, v2) {
  return v1 + v2;

To test it, we should have to call method test, for example like

test("2+2=4", function() {
  var result = sum(2, 2);
  equals(4, result);

If your code accesses some html element, there are several options - you can include your real html code into tests.html body, or you can mock it with some trivial html element. You can also add and destroy necessary html elements in test scenario. In general, include is probably best option as it avoids dublication, but simple mock elements was best choise in my cases so far. Drawbacks of include is that it requires server-side code and calls.
For example, if your code is

function showSum(v1, v2) {
  $('#result').text(sum(v1, v2));

You can add div element with id 'result'. And now all your tests will look like:

    <script src="jquery-1.3.2.js"></script>
    <script src="testrunner.js"></script>
    <script type="text/javascript" src="code.js" ></script>
    <link rel="stylesheet" href="testsuite.css" type="text/css"/>
    <script type="text/javascript">
      test("2+2=4", function() {
        var result = sum(2, 2);
        equals(4, result);
      test("show 2+2=4", function() {
        showSum(2, 2);
        equals(4, $('#result').text());
    <ol id="tests"></ol>
    <div id="main"></div>
    <div id="result"></div>

Now we have some state between tests (value in 'result' div) and it is not good, because it can confuse tests and bring some surprizes.
Traditional way how to clean state between tests is to reset it. It is normally done in methods setup or teardown.
Setup is called before every test and supposed to prepare test for running and teardown is called after every test and supposed to clean environment after test.
In QUnit it is set in function 'module', like this:

module("my tests", {
  setup: function() {
  teardown: function() {

Here we set result to some value, for example, to check that it really updates value, but not appends. And in teardown we reset 'result' div to it's initial empty state for next test. It usually has more sence in big projects with many state parameters.

localStorage returns undefined value

When I have just started to work with localStoage without reading much about it I have created something like this
localStorage['key'] = 'value';
Result was great, and I got nice alert with 'value' on it.
Quite excited, i created functionality i wanted to have, created nice tests and found out that something is not great at all and after localizing error I have found out that similar piece of code is not working as good as previous.
localStorage['key'] = {test:'value'};

In this case, alert returned 'undefined', but not 'value', what was quite unexpected.
However this code
localStorage['key'] = {test:'value'};
says that I have nice '[object Object]'. I checked it a bit and had found that this script
localStorage['key'] = {test:'value'};
alert(typeof localStorage['key']);
says that my localStorage result is in fact 'string', which was quite unexpected, as it should be Object.
As it turned out, localStorage uses structured clone algorithm and whether because of this or for some other reason it converts my object into string, stores it as such and therefore looses all properties and values.
Finally, I have found easy way to solve this problem by converting my object into JSON string. Fortunately Firefox have native JSON coverter functions and everything can be done simply like
localStorage['key'] = JSON.stringify({test:'value'});
In WRT there is no such nice lib, but it is possible to download it at And it can be nicely used like this:
widget.setPreferenceForKey(JSON.stringify({test:'value'}), 'key');
There is small issue though. As you see JSON lib is used to convert object to string, but it was not able to convert string to object on my Nokia device. But this small eval hack still works great and I am getting my value as expected.

Let's start

Today I start this blog. I have created articles here and there before, but never in some organized way. So I'll try to put everything about programming, software and internet that can be related to my professional development.