Back To The Front

Thoughts on developing server side and client side apps

Decent Exposure Gem, Mongoid and Find_by Method

Decent Exposure is ‘a Ruby gem for cleaner controllers’ and I love it. As for now, hovewer, it lacks a strategy for use with Mongoid. In most basic cases a strategy for ActiveRecord works fine, but it breaks when one needs to use a custom finder. That is because Mongoid doesn’t provide dynamic finders – instead of ActiveRecord style

1
Article.find_by_name('foo')

(which will be deprecated in Rails 4 AFAIK) we use

1
Article.find_by(name: 'foo')

I wrote a simple initializer which monkey-patches decent_exposure allowing us to use lambda as a ‘finder’ option, like this

1
expose :article, finder: lambda { |c| find_by(name: c.params[:id]) }

Just drop these lines of code into config/initializers/decent_exposure_mongoid.r

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
module DecentExposure
  class ActiveRecordStrategy < Strategy
    def singular_resource
      if id
        case finder
          when Symbol
            scope.send(finder, id)
          when Proc
            scope.instance_exec(controller, &finder)
          else
            raise "Symbol or Proc needed"
        end

      else
        scope.new
      end
    end
  end
end

ActiveRecord Dynamic Attributes as Serializable Struct

ActiveRecord gives us a nice feature to store dynamic attributes in a single database column

1
2
3
class Product < ActiveRecord::Base
  serialize :props, Hash
end

If you use it often it may be a sign that you should think about a different storage than a database. But sometimes it is convenient to denormalize your data.

If you don’t know your attributes until runtime, it is the way to go. But sometimes you know them, but still want to denormalize for some reasons.

Asynchronous Singleton API

After an awesome tech talk with @petermichaux, @racino, @varjs, @qvist, we came to an interesting point, as how to handle a certain situation:

  • you need a singleton

  • you need it to instantiate lazily

  • its instantiation involves querying server-side, thus you only want to do it when it’s absolutely necessary (hence the lazy approach)

  • obviously, many parts of the system may be wanting to use what that singleton offers, in any given order, at any given time

What problems does this pose? It is somewhat similar to what is encountered in Java, where threads are involved. You would probably want the getInstance method to be synchronized. This is to some extent also true in case of the lazy, asynchronous instantiation in JavaScript. Because what happens, when getInstance is called multiple times, before instantiation is finished? Bad, unpredictable things.

This could seem as an obvious call for the deferred approach. But what got cooked rather resembled the state machine. So, enough talking, let’s code!

Passing the singleton object instance

We cannot get the singleton and assign it immediately, like so

1
var mySingletonInstance = MySingleton.getInstance();

since it might not return anything at that point. We need to do it using callbacks passed to the instantiation logic, which get called when the job gets done. So we would rather go like this when using the singleton

1
2
3
4
5
6
7
8
MySingleton.getInstance({
    success : function(singletonInstance) {
        // here we get access to our desired instance
    },
    failure : function(error) {
        // bugger, something went wrong
    }
});

Concurrent singleton instance access

All cool, but we still need to handle the case where multiple other parts of the system request access to the instance before it gets created. Like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// in module foo
MySingleton.getInstance({
    success : function(singletonInstance) {
        // do something useful with what the server provided
    },
    failure : function(error) {
        // bugger, something went wrong
    }
});

// in module bar
MySingleton.getInstance({
    success : function(singletonInstance) {
        // do something just as useful
    },
    failure : function(error) {
        // bugger, something went wrong
    }
});

Callback queue

What we need be doing, is collect all the callbacks, and execute them once the object is ready to be used. So let’s build up a skeleton of the solution

1
2
3
4
5
6
7
8
9
10
var MySingleton = {};
(function() {
    var callbackQueue = [];
    var instance = null;
    var doRequests = function(callbacks) {
        //code for interaction with the server
    };
    MySingleton.getInstance = function(callbacks) {
    }
}());

States

Let’s think about what state our singleton can be in. One is before instantiation, which you could call before. When it’s called for its instance, it could be working. Once all is done it could be success, and if something went wrong, failure. Extending our skeleton with the states

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var MySingleton = {};
(function() {
    var state = "before";
    var callbackQueue = [];
    var instance = null;
    var doRequests = function(callbacks) {
        //code for interaction with the server
    };
    MySingleton.getInstance = function(callbacks) {
        switch (state) {
            case "before":
                //this would be the case of the first call for the instance; here we start instantiating and queue up the first callback
                state = "working";
                callbackQueue.push(callbacks);
                break;
            case "working":
            //here we just queue up further callbacks
            case "success":
            //in this case we execute the success callback immediately
            case "failure":
            //like in success, but we pass some custom error object to the failure callback
            default:
                throw new Error("Invalid state: " + state)
        }
    };
}());

Asynchronous instantiation

One extra thing we’ve got to remember is that the instantiation itself, due to its asynchronous nature, also happens with the help of callbacks, hence the extra handling of them in the before branch

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
var MySingleton = {};
(function() {
    var state = "before";
    var callbackQueue = [];
    var myInstance = null;
    var error = null;
    var doRequests = function(callbacks) {
        //code for interaction with the server
    };
    MySingleton.getInstance = function(callbacks) {
        switch (state) {
            case "before":
                state = "working";
                callbackQueue.push(callbacks);
                doRequests({
                    success : function(singletonInstance) {
                        state = "success";
                        myInstance = singletonInstance;
                    },
                    failure : function(errorObj) {
                        state = "failure";
                        error = errorObj;
                    }
                });
                break;
            case "working":
            //here we just queue up further callbacks
            case "success":
            //in this case we execute the callback immediately
            case "failure":
            //like in success, but we pass some custom error object
            default:
                throw new Error("Invalid state: " + state)
        }
    };
}());

Resolving callback queue

Now let’s take care of resolving the callback queue. Throughout this article, I’ve been assuming the callbacks were passed in form of an object like

1
2
3
4
5
6
MySingleton.getInstance({
    success : function(singletonInstance) {
    },
    failure : function(error) {
    }
});

So here goes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
var MySingleton = {};
(function() {
    var state = "before";
    var callbackQueue = [];
    var myInstance = null;
    var error = null;
    var doRequests = function(callbacks) {
        //code for interaction with the server
    };
    MySingleton.getInstance = function(callbacks) {
        switch (state) {
            case "before":
                state = "working";
                callbackQueue.push(callbacks);
                doRequests({
                    success : function(singletonInstance) {
                        state = "success";
                        myInstance = singletonInstance;
                        for (var i = 0, ilen = callbackQueue.length; i < ilen; i++) {
                            callbackQueue[i].success(myInstance);
                        }
                        callbackQueue = [];
                    },
                    failure : function(errorObj) {
                        state = "failure";
                        error = errorObj;
                        for (var i = 0, ilen = callbackQueue.length; i < ilen; i++) {
                            callbackQueue[i].failure(error);
                        }
                        callbackQueue = [];
                    }
                });
                break;
            case "working":
            //here we just queue up further callbacks
            case "success":
            //in this case we execute the callback immediately
            case "failure":
            //like in success, but we pass some custom error object
            default:
                throw new Error("Invalid state: " + state)
        }
    };
}());

Final solution

Let’s build the rest of the state branches

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
var MySingleton = {};
(function() {
    var state = "before";
    var callbackQueue = [];
    var myInstance = null;
    var error = null;
    var doRequests = function(callbacks) {
        //code for interaction with the server
    };
    MySingleton.getInstance = function(callbacks) {
        switch (state) {
            case "before":
                state = "working";
                callbackQueue.push(callbacks);
                doRequests({
                    success : function(singletonInstance) {
                        state = "success";
                        myInstance = singletonInstance;
                        for (var i = 0, ilen = callbackQueue.length; i < ilen; i++) {
                            callbackQueue[i].success(myInstance);
                        }
                        callbackQueue = [];
                    },
                    failure : function(errorObj) {
                        state = "failure";
                        error = errorObj;
                        for (var i = 0, ilen = callbackQueue.length; i < ilen; i++) {
                            callbackQueue[i].failure(error);
                        }
                        callbackQueue = [];
                    }
                });
                break;
            case "working":
                callbackQueue.push(callbacks);
                break;
            case "success":
                callbacks.success(myInstance);
                break;
            case "failure":
                callbacks.failure(error);
                break;
            default:
                throw new Error("Invalid state: " + state)
        }
    };
}());

We’re done!

And that’s about it! Further improvements may include making MySingleton and its getInstance protected against overwriting. To achieve this, we could use ES5 object and property descriptors, some of which I’ve already covered.

ES5 in My App: Impregnable Namespaces, Getters and Setters

NOTE: this will only work within a JavaScript runtime supporting ECMAScript 5. To check, what the situation looks like across browsers, check out Kangax’s ES5 compatibility table

Using ES5 property descriptors, or rather relying upon their default values, we can attach our application code to the global namespace and prevent it from being overwritten. Consider this piece of code

1
2
3
4
5
(function(global) {
    Object.defineProperty(global, "MyApp", {
        value: {}
    });
}(this));

Considering the defaults, we get ourselves an object under the global called “MyApp”, which is guaranteed to be accessible under that very name. Always. According to the specs, if you later do something like

1
2
3
(function(global) {
    global["MyApp"] = "MyNewApp";
}(this));

then global["MyApp"] still points to the same object, albeit no error is thrown, which makes me a little sad. Anyway, that shouldn’t be a collision very hard to debug. So, in effect, we got as a globally accessible MyApp object, ready to be filled with parts of our app.

If you have anything that acts sort of singleton-like (eg. an overlay mechanism), you could add that to MyApp, and also prevent it from being overwritten

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
(function() {
//  initialization code
    var setContent = function(content) {
//      ...
    };
    var getContent = function() {
//      ...
    };

    var show = function(content) {
//      ...
    };
    var hide = function() {
//      ...
    };
    Object.defineProperty(MyApp, "overlay", {
        value: {
            show: show,
            hide: hide,
            setContent: setContent
        }
    });
}());

The defaults again make the property “overlay” of the MyApp object point to the same value, even if you try to overwrite it. Obviously, if there is too much being set to “read only”, you will probably end up not being able to use other programming techniques, like maybe inheriting, mixing in, or other. Protect your code only as much as necessary, but not less ;)

Another interesting thing for how to utilize Object goodness of ES5, is setters and getters. Imagine we have a news ticker on our site, which could also be singletonish. We set it up

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
(function() {
//  initialization code
    var rootEl = document.createElement("div");
//  attaching ticker rootEl wherever it belongs
    var fade = function(dir){
//      some visual effects we may want to come in play when setting
    }
    var setContent = function(content) {
        fade("out");
        rootEl.innerHTML = content;
        fade("in");
    };
    var getContent = function() {
        return rootEl.innerHTML;
    };
    Object.defineProperty(MyApp, "ticker", {
        set: setContent,
        get: getContent
    });
}());

To change the content of a DOM node, we just set the value of our MyApp.ticker, eg.

1
MyApp.ticker = "Some grand breaking news yay!";

Pretty simple, and definitely aiding in code stability and encapsulation.

The Classic Game of Life in JavaScript With Framework-less MVC

It turns out, you don’t need any library to build a MVC app. You can do this totally in vanilla JS. Of course, the more complex your app, the more abstraction will be required, where some aids already available may come in handy (why reinvent the wheel?). But no need to include ~300kB libraries just to do simple games or the likes.

The Game of Life is a cool example. For the rules of it, please read the Wikipedia article. See it in action:

Please consider the source code.

My point here is not much more but utilizing a couple patterns:

The view, LifeView.js, will be drawn using

<canvas>

The controller, LifeGame.js, will invoke an interval, which will call a method to recalculate the whole model a couple of times a second. The model, BlockSet.js, will be a simple 2D array, with a few helper methods, like iteration of the surrounding of a given cell.

I programmed it object oriented, using prototypal inheritance. M, V and C will communicate using the PubSub pattern, for which I used a simple 3rd party implementation — Morgan Rodericks PubSub. It’s very simplistic, and covers all needs in regard of this project (the point at which more often than not people fail to recognize what is the right thing to depend on).

PubSub adds to the value of decoupling code. Once the controller is done modifying the model, it publishes a “frame” message, to which the view listens to, and when it happens, reads data from the model to draw it on canvas. As an added bonus, I took advantage of what MVC can give you, and added a feature of drawing on the view. If you click and drag on the surface, you add live cells. I recommend not doing it while the thing is running, as a 3x3 block of cells (which I designed it to behave like) dies pretty fast, and its hard to see the effect. Please stop the cycle fist, clear it, and draw. Then start, and see how it lives. To me it was quite some fun :) Now, how to do it keeping our layers separated? Again, PubSub comes to save the day. The LifeView makes the canvas element listen to mouse events, and publishes a “draw” message with relevant [x,y] data. The controller listens to that message, and makes changes in the model according to the data passed. During the next “frame” event, the modified data from the model gets reflected upon the view. This way, we have ourselves a nice bi-directional communication example between our layers.

Finally we come to the idea of dependency injection. This is also pretty simple, once you get to do it. The LifeView depends on the LifeGame. Instead of breaking the direction of dependency, and passing the view to the game, we do the exact opposite. The dependency of LifeGame is injected into LifeView

1
2
var game = new LifeGame(400, 400);
var view = new LifeView(canvas, game, 2);

The same happens with the canvas element, on which the view depends on.

As an exercise in MVC, I might recommend to try to remove the drawing feature, and then add it yourself. To me, it was a very distinct task showcasing the undeniable benefits of the MVC design.

Leaving Enterprise Java for Ruby on Rails (Part 2)

ActiveRecord vs Hibernate

ActiveRecord uses different approach to achieve the O/R mapping. It’s based on Rails core concept: convention over configuration. It uses database metadata and thanks to Ruby’s dynamic nature columns are mapped to object properties at runtime. All we need is to obey some conventions (we can override them if we need to) and to define relationships

1
2
3
4
5
6
7
class Product < ActiveRecord::Base
   belongs_to :category
end

class Category < ActiveRecord::Base
   has_many :products
end

Asumming we have ‘products’ and ‘categories’ tables in our database, that’s all.

In Hibernate You probably don’t want to have a Product collection inside Category. Usage of Hibernate collections is very limited. In Hibernate, if you do something like this

1
category.getProducts().size();

It results in:

[sql] select * from products where category_id = ? [/sql]

You can’t do anything useful with Hibernate collections. Their main purpose is to use them in HQL/Criteria API. ActiveRecord is much smarter than that. We can write

1
2
3
4
category.products.count
category.products.any?
category.products.order('created_at')
category.products.sum(:price)

and it results in:

[sql] select count() from products where category_id = ? select count() from products where category_id = ? select * from products where category_id = ? order by created_at select sum(price) from products where category_id = ? [/sql]

ActiveRecord automatically generates finder methods for You, so for simple scenarios you can query for objects like this

1
2
Product.find_by_name('Milk')
Client.find_by_firstname_and_status('Jan', :active)

Of course all of advanced Hibernate features have their equivalents. We have interceptors, observers, caches, validations, locking etc. Albeit advanced those features are kept simple and usable. Let’s look at callbacks

1
2
3
4
5
6
7
class Category < ActiveRecord::Base
   before_destroy :check_products

   def check_products
      raise 'Remove products first' if products.any?
   end
end

Checking for dirty attributes is very easy

1
2
3
4
5
6
7
8
9
10
> p = Product.first
#<Product id: 1, name: "Beer", price: 10>
> p.changed?
false
> p.price += 10
20
> p.changed?
true
> p.changes
{"price"=>[10, 20]}

It is worth mentioning that there are many gems extending ActiveRecord capabilities. For example, to model a category tree we only need to install ‘acts_as_tree’ gem and instruct Category class to use it

1
2
3
class Category < ActiveRecord::Base
   acts_as_tree
end

From now on we have access to some additional methods

1
2
cat.parent
cat.children

We can chain ‘children’ with AR methods the same way we did it with plain AR collections

1
cat.children.where(:status => :active).order(:created_at)

Wrapping it up:

  • No explicit O/R mappings

  • No need for DAO classes; you put all in your models

  • No need for another query language; most of the time you just call methods, falling back to SQL fragments in some cases

Leaving Enterprise Java for Ruby on Rails (Part 1)

I was charmed by the elegance, simplicity* and expressiveness of Ruby since the first time I saw it. But I was constantly too busy fighting with variety of Java related stuff. Life of a JEE developer ain’t easy. It’s not rocket science, but there are some pretty hard and annoying difficulties.

Java language itself has had its best times. Some design decisions made things even harder than in C++, namely lack of operator overloading, which makes operations on BigDecimals a nightmare. Similary, dealing with Strings is absurdly complicated, due to lack of regular expression handling on the language level and poor choice of built-in methods. Of course there are third party libraries which try to make things easier, but they cause ugly, non object-oriented code. Same things with dates. One of worse designed things in Java. Yes, there is Yoda Time, but such basic stuff should be included in a standard library. Same with Lists and Maps. You have to write tons of boilerplate code just to create a list with some elements. Maps are even worse. Iterating over collections became little easier since Java 5, but is still far from perfect due to lack of closures. To make things even worse, we were honored with introduction of generics, which are IMO one of the biggest mistakes brought to Java. Yes, there are some good uses of generics, but they are rarely seen. They brought no real value, they are complicated and thus poorly understood by developers, which caused not very concise code to become even more verbose, filled with dozens of < <>>< ?>. Primitives are a real pain in the ass, and autowrapping didn’t entirely fix it. To be fair I have to admit that annotations are cool, making some metaprogramming possible. Unfortunatelly, besides framework-specific annotations the most widely used annotation is @SupressWarnings.

Few months ago I started two projects using RoR and instantly became a huge enthusiast. I decided to write a short series of articles explaining why working with Ruby and RoR is so much fun. It’s not meant to be a ruby guide nor a migration guide.

The Ruby Language

Let’s write a sample method in Java, creating a map and then building a string using its entries and then returning it

1
2
3
4
5
6
7
8
9
10
11
12
13
public String foo() {
  Map m = new LinkedHashMap();
  m.put("foo", "bar");
  m.put("John", "Doe");
  m.put("xxx", "yyy");
  StringBuilder sb = new StringBuilder();
  for (String k : m.keySet()) {
      String v = m.get(k);
      sb.append(k + "_" + v + ", ");
  }
  sb.setLength(sb.length() - 2);
  return sb.toString();
}

And now the equivalent in Ruby

1
2
3
4
5
def foo
 m = { 'foo' => 'bar', 'John' => 'Doe', 'xxx' => 'yyy' }
 s = m.inject(String.new) do |s, kv|
 s << "#{kv[0]}_#{kv[1]}, "  end  s[0...-2]
end

We can even write it as one-liner and it is still quite clear

1
2
3
def foo
 { 'foo' => 'bar', 'John' => 'Doe', 'xxx' => 'yyy' }.inject(String.new) { |s,kv| s += "#{kv[0]}_#{kv[1]}, " }[0...-2]
end

This code is silly, but it shows us some interesting things about Ruby. At first glance its obvious that Ruby code is shorter. (Yes, maybe the Java version could be little bit shorter. We can just concatenate strings instead of using StringBuffer, but i wrote it that way because its a well known idiom. Also note that to actually run Java code you need to wrap all this in some class and write a main() method ) Closer look reveals other interesting stuff:

  • Ruby uses dynamic typing

  • Ruby has closures

  • Ruby has nice syntax for creating a Hash

  • String literals are interpolated

  • There are nice built-in operators for a String

  • Strings are mutable

  • Methods return last evaluated expression

Ruby allows us to desing very elegant APIs. This is largely due to the way Ruby treats method calls and arguments. Method arguments can have default values

1
2
3
4
def find_products(category, limit = 10) end

find_products('milk')
find_products('yoghurt', 20)

To imitate this in Java we need overloading

1
2
3
4
5
def find_products(category, options = {})
end

find_products('milk')
find_products('milk', :fresh => true, :fat => [0..2])

There is no reasonable way to do same thing in Java.

In Ruby everything is an object. There are no primitives

1
2
> 1.class
Fixnum

It allows some interesting constructs

1
2
3
3.times do |i|
   puts i
end

Forget using static methods from Math utility class and awkward operations on BigDecimal-

1
2
3
4
5
6
> a = 10 / 3.0
3.3333333333333335
> a.floor
3
> a.ceil
4

Arrays have many useful features

1
2
3
4
5
6
7
8
> [1,5,3,7,2].sort
[1, 2, 3, 5, 7]
> ['foo', 'bar'].sort
['bar', 'foo']
> [1,5,2,3].max
5
> [1,2,9,3].keep_if { |i| i.even? }
[2]

I will move to Rails in folowing parts.

  • Well, regarding the simplicity. Ruby offers so many ways to achieve things, that it is possible to write a really ugly, cryptic, hard to understand code, albeit every tool can be misused. You can kill with a loaf of bread if you try hard enough :) Some libraries using more sophisticated stuff, like ActiveRecord, can also look cryptic at the first glance.

Storing Sets of Key/value Pairs in a Single Db Column With Hibernate Using PostgreSQL Hstore Type

Few years ago I was working on a platform for creating classified ads websites. It was an international project and first implementation of our website was in Russia – 140 millions people, so performance was our main concern.

Our platform was based on a J2EE webapp with Struts(ouch), Spring 2, Hibernate 2 and a PostgreSQL (7.x AFAIR) cluster.

Ads were categorized and each ad had a set of attributes(key/value pairs) dependend of category they belonged. Our first approach was to model it using a table with each row representing one key/value pair, but – long story short – it didn’t perform well.

Then our DBA came with a solution: Hstore – contrib module for storing (key,value) pairs You can read more about hstore in PostgreSQL reference, as since version 8.2 it is a part of a distribution.

You can also read some articles about hstore on Depesz’s Blog (two oldest posts are in polish).

Our classified ads websites were successfully deployed in many european countries, and our solution performed good. It was all in 2006. Recently I was considering hstore in my project based on Ruby On Rails. I googled quickly how to handle hstore in RoR, there was even a plugin ready for download on Github. I was curious if there is currently any solution for Hibernate, but I found nothing. So I decided to sit and write this article. I don’t have access to the source code of our old platform, and it was in the dark ages of Java 1.4, Hibernate 2, XDoclet and other terrible things, so I wrote some code from the scratch. Basically there are two approaches:

  • implementing own UserType and map a field to a column using @Column

  • mark field as @Transient and handle it via JDBC, maybe using some interceptors

I will cover the first approach. I assume You got the idea of hstore and i will focus only on Hibernate code. Lets write a helper for converting a Map to a String conforming to hstore syntax and vice versa

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class HstoreHelper {

  private static final String K_V_SEPARATOR = "=>";

  public static String toString(Map<String, String> m) {
      if (m.isEmpty()) {
          return "";
      }
      StringBuilder sb = new StringBuilder();
      int n = m.size();
      for (String key : m.keySet()) {
          sb.append(key + K_V_SEPARATOR + m.get(key));
          if (n > 1) {
              sb.append(", ");
              n--;
          }
      }
      return sb.toString();
  }

  public static Map<String, String> toMap(String s) {
      Map<String, String> m = new HashMap<String, String>();
      if (! StringUtils.hasText(s)) {
          return m;
      }
      String[] tokens = s.split(", ");
      for (String token : tokens) {
          String[] kv = token.split(K_V_SEPARATOR);
          String k = kv[0];
          k = k.trim().substring(1, k.length() - 2);
          String v = kv[1];
          v = v.trim().substring(1, v.length() - 2);
          m.put(k, v);
      }
      return m;
  }
}

Here are some basic tests

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class HstoreHelperTest {
  
  @Test
  public void testEmptyMapToString() {
      Map m = new HashMap();
      assertEquals("", HstoreHelper.toString(m));
  }

  @Test
  public void testToString() {
      Map m = new HashMap();
      m.put("foo", "bar");
      assertEquals("foo=>bar", HstoreHelper.toString(m));
  }
  
  @Test
  public void testToString2() {
      Map m = new LinkedHashMap();
      m.put("foo", "bar");
      m.put("xxx", "yyy");
      assertEquals("foo=>bar, xxx=>yyy", HstoreHelper.toString(m));
  }
  
  @Test
  public void testEmptyStringToMap() {
      Map m = HstoreHelper.toMap("");
      assert(m.isEmpty());
  }
  
  @Test
  public void testToMap() {
      Map m = HstoreHelper.toMap("\"foo\" => \"bar\"");
      assertEquals(1, m.size());
      assertEquals("bar", m.get("foo"));
  }
  
  @Test
  public void testToMap2() {
      Map m = HstoreHelper.toMap("\"foo\" => \"bar\", \"xxx\" => \"yyy\"");
      assertEquals(2, m.size());
      assertEquals("bar", m.get("foo"));
      assertEquals("yyy", m.get("xxx"));
  }
}

And now a UserType implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
public class HstoreUserType implements UserType {

  public Object assemble(Serializable cached, Object owner)
          throws HibernateException {
      return cached;
  }

  public Object deepCopy(Object o) throws HibernateException {
      // It's not a true deep copy, but we store only String instances, and they
      // are immutable, so it should be OK
      Map m = (Map) o;
      return new HashMap(m);
  }

  public Serializable disassemble(Object o) throws HibernateException {
      return (Serializable) o;
  }

  public boolean equals(Object o1, Object o2) throws HibernateException {
      Map m1 = (Map) o1;
      Map m2 = (Map) o2;
      return m1.equals(m2);
  }

  public int hashCode(Object o) throws HibernateException {
      return o.hashCode();
  }

  public boolean isMutable() {
      return true;
  }

  public Object nullSafeGet(ResultSet rs, String[] arg1, Object arg2)
          throws HibernateException, SQLException {
      String col = arg1[0];
      String val = rs.getString(col);
      return HstoreHelper.toMap(val);
  }

  public void nullSafeSet(PreparedStatement ps, Object obj, int i)
          throws HibernateException, SQLException {
      String s = HstoreHelper.toString((Map) obj);
      ps.setObject(i, s, Types.OTHER);
  }

  public Object replace(Object original, Object target, Object owner)
          throws HibernateException {
      return original;
  }

  public Class returnedClass() {
      return Map.class;
  }

  public int[] sqlTypes() {
      /*
      * i'm not sure what value should be used here, but it works, AFAIK only
      * length of this array matters, as it is a column span (1 in our case)
      */
      return new int[] { Types.INTEGER };
  }
}

Finally, let’s annotate our entity bean

1
2
3
4
5
6
7
8
9
10
11
@Entity
@TypeDef(name = "hstore", typeClass = HstoreUserType.class)
public class Item {
    [...]

    @Type(type = "hstore")
    @Column(columnDefinition = "hstore not null")
    private Map<String, String> properties = new HashMap<String, String>();

    [...]
}

Some things to take into consideration:

  • This is not a complete solution, I just wanted to show You how to do it. I made only basic integration tests.

  • Maybe it would be better to use LinkedHashMap or some other sort of Map that preserves order.

  • It handles only String values, if You need some other types you need to convert them on your own

  • Some HstoreUserType methods should check for null values (e.g. nullSafeGet, nullSafeSet), but I assumed ‘properties’ to be not null, to make code shorter

When writing this article I was using:

  • Hibernate 3.6.0

  • PostgreSQL 8.4.8

  • PostgreSQL JDBC driver 8.4-701.jdbc4

Please leave some feedback if it helped You, maybe some day I will make it complete and package it as a JAR.

The Package Manager for Mac

Few days ago I was trying to get a Rails project working on my Mac, in conjunction with a PostgreSQL database. This is a short attempt to save others from wasting hours on setting up.

Back to the Front

Life’s been keeping me busy, that’s for sure. I still want to write some quality stuff for this site, and to make itself look good as well.

Recently I had some spare time, finally, and decided to give this blog a temporary face-lift and get rid of the abysmal Magazeen Wordpress theme. I am mentioning this because I am preparing a custom made skin, heavily relying on bleeding edge CSS3 goodness (with total disregard for older browsers). Built with Compass of course. And in the same time, I’m writing down all the steps to a new Wordpress skin for a 2-3 post series — kind of „do it yourself”.

Another piece of news is that I’ve been heavily inspired by the works of Peter Michaux, especially his MVC approach to writing JavaScript applications, and therefore started working on a project of mine which I call „Scratchbox MVC” — a true backbone for laying out code for anything in between tiny and huge, environment independent (be it a server-side app, client-side code, a CLI tool, or a browser plugin). It will conform to the module spec of CommonJS, and that will be the reason behind exactly one dependency — RequireJS — which makes it possible to have modules loaded in the browser. No unnecessary piece of code, other than that (if you build for the browser, of course) will be shoved down your throat. No syntactic sugar, no pretending this is not JavaScript. Side by side I’ll be working on a range of modules, which will enable carrying out common tasks, so as to grant more of an out-of-the-box experience, if one wishes for such. I intend to put together a simple distribution tool, where you’d either grab the vanilla core, choose common packages, or build your own. Hell of a project in fact, yet this is something I have always been missing in the world of JS. Sure, there’s stuff like Backbone.js, but it already includes underscore.js, and gives you their solution for way too many things. Of course, this may be the thing for many people, but I aim for something else, more elastic, not bloated, and minimalistic to the max. As a bottom line, it will make it possible for people to start from scrath, or use out of the box solutions in form of add-on modules. Hence the name, Scratchbox.

I will continue this topic by posting the main goals of this project in form of a mind map, so if you will be feeling like pointing out misconceptions, or just root for this venture, you will have an opportunity to speak your mind.