Tuesday, June 14, 2011

OrientDB - Pure Java NoSQL Datastore

I have been following the so-called 'NoSQL movement' (as if such a movement exists!). In my opinion, it is just another way of storing and retrieving data. And this new (rather different, I am sure the method is not new) way is only suitable for certain type of applications. Not all applications require NoSQL-type storage and retrieval regardless of those who claim it to be. SQL and NoSQL complement each other. They are not rivals. 

Having said that, I was pretty much interested in the concepts. I love trying out new things. While I was planning the design and architecture of a new open source project that I intend to develop (It is not exactly new. I have already started it but now plan to move it to a new architecture - Greenscape), one of the choices I had to make was on the data storage. My application will be highly dynamic with ability of end users to add and remove columns to a database table frequently. Doing it in relational database will incur heavy performance and complexity. After much consideration, I decided that a non-relational database will be the best choice for my application. But this choice is not without its share of challenges:
  1. I loose JPA/Hibernate support which means I may have to come up with an equivalent framework.
  2. I loose portability. NoSQL is non-standard. There is no standard query language. There are no standard protocol. So, tomorrow, I cannot replace the database with a better performing one without rewriting my application.
  3. Few documentation. What are the best practices, design patterns, etc?
In spite of the challenges, I went ahead with my choice. The compelling reason was the ability to create knowledge because of the void.

Now that the decision was made, I had to choose a NoSQL database. I analysed all the popular ones but none fitted my requirements. I had one criteria for selecting a database: I must be able to code in Java. Most available systems were non-Java based which would be a significant issue for a one man project. Even if they had Java interface, the installation, setup, etc. were a tedious process. Having a database developed purely in Java has many advantages:
  1. Easy packaging with other applications
  2. Easy to install and run
  3. Can be embedded
  4. Can run in same or different VM
  5. Easy to debug
  6. Easy to test
After much searching, I came across OrientDB. Voila! That was what I needed! Going through its features only reinforced by belief in it. It is a pure Java solution and very small in size (500KB! 2MB since last release) . It can be embedded as well as deployed in networked mode. It is both schema-less and schema-based! This topped the feature list. It also supports SQL as a query language (Hmm, need to call NoSQL by some other name).

Some of the features taken from its homepage:

  1. SQL
  2. Super fast
  3. Transactional
  4. GraphDB
  5. Web ready (HTTP, REST, JSON)
  6. Everywhere (Pure Java)
  7. Extremely light
  8. Apache License (Here's the money)

End of architecture choice 1 for Greenscape.
Next decision on application framework pending.

Saturday, February 19, 2011

Grow Up Java! Proposing Java Desktop Edition

No, this is not another 'Java is Dead' rant. Java is very much alive and kicking. It is one of the best development and runtime platform available. By far the most stable platform of those. And that might just be its biggest bane. Ridiculous! How is stability a bane? You might ask. Well, you can see the slow progress in path breaking innovation, due to it. See the debate on closures and the progress on module system/OSGI.

The Java platform is growing only by a few APIs and small language changes/additions every year. There is no major big innovation happening. All the major changes that has been happening are outside it. Be it the  Dependency Injection, Persistence API, Scripting API, Desktop API, Application Framework API, they were only added to the platform subsequently. But they are just APIs. What we need is something big. Something that is 10 years advanced than today.

What I feel is Java is advancing in a bottom-up fashion. Small and slow changes at a time. What we need is a top-down approach. Think futuristic, design it and then only implement it in a bottom-up approach.

Take the example of new Swing Application Framework (now dropped from the standard). I think this new framework is a poorly envisioned idea. Look at the poor state of JMF. No substantial progress can be made on the desktop without support for multimedia. Yes, JavaFX is coming soon (for 3+ years ?). It is a big step forward but is not a standard (yet. Will it be ever?).

We have the JavaSE and JavaEE is built on top of it. Why can't we do the same with the desktop? Why can't we have something like the Java Desktop Edition or JavaDE ? Put all the big stuffs here. In this way, we can keep the JavaSE simple. Language and VM changes goes into JavaSE. Common APIs applicable to both EE and 'DE' goes into SE. But desktop additions like application framework, multimedia, browsing capabilities, gadget bar?, JavaFX, etc. goes into 'DE'. Of course, JavaME also needs to be considered but since industry's mood is to bring SE to ME, they can be considered the same for the sake of this blog.

Some might argue that the desktop is becoming irrelevant with the popularity of web applications and powerful browsers (with HTML 5). But as any unbiased report will say, the irrelevance of desktop will not happen anytime soon. After all, the browser needs to run on a desktop!

Basically, Java Desktop Edition becomes the new Operating System. It should have transparent integration with the underlying OS. Have functionalities in the form of services and modules on the lines of OSGI. So everything is a service: print service, document service, file service, graphic service, database service, < add your favorite services here >. So advanced capabilities can be exposed as a service to any module or applications (collection of modules) in the system. Imagine having Eclipse plugins as services exposed to all applications.

Think of the innovative possibilities of a Java Desktop (heard it before?):
- Java Browser with built-in support for applets, JavaFX - we can have applet plugins
- Browser can be embedded in any application
- GIMP like editor - JIMP?
- Standard installer for all applications - No OS specific versions of Eclipse or Netbeans (Java WAS supposed to be Write Once, Run Everywhere)
- Finally, a Java media player
- Desktop gadget bar
- Java Office
- < your favorite application here >

It is time for Java to grow up and act its age.

Thursday, January 27, 2011

Liferay (s)mashup - Google Maps

In the previous blog, we saw how to fire events asynchronously on the client side. In this blog, we will see the integration of Google Maps in a portlet.
Showing Google Maps in a portlet is a breeze. For this, create a portlet called 'Visual View'. This portlet displays the Google Map for visual interaction. It receives the source and destination from the Plan Your Travel portlet and shows the road route in the map.

Using Google Maps API

Google Maps API is a collection of web services providing geographic data for creating maps applications. These web services use HTTP requests to specific URLs, passing URL parameters as arguments to the services. Generally, these services return data in the HTTP request as either JSON or XML for parsing and/or processing by an application.  Let's get straight to the code.

Code Listing

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%>
<portlet:defineObjects />
<style type="text/css">
#map_canvas {
    height: 500px;
    width: 400px

<script type="text/javascript">
    var <portlet:namespace />map;
    var <portlet:namespace />geocoder;
    var <portlet:namespace />directionDisplay;
    var <portlet:namespace />directionsService;
    var <portlet:namespace />rendererOptions = {
        draggable : true //make the map points draggable
    var <portlet:namespace />initialLocation;
    var <portlet:namespace />infowindow;

    function <portlet:namespace />initialize() {
        var myLatlng = new google.maps.LatLng(-34.397, 150.644);
        var myOptions = {
            zoom : 8,
            center : myLatlng,
            mapTypeId : google.maps.MapTypeId.ROADMAP

        <portlet:namespace />map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        <portlet:namespace />geocoder = new google.maps.Geocoder();
        <portlet:namespace />directionsService = new google.maps.DirectionsService();
        <portlet:namespace />directionsDisplay = new google.maps.DirectionsRenderer(
                                                    <portlet:namespace />rendererOptions);
        <portlet:namespace />directionsDisplay.setMap(<portlet:namespace />map);
        <portlet:namespace />infowindow = new google.maps.InfoWindow();

        //geo location
        // Try W3C Geolocation method (Preferred)
        if (navigator.geolocation) {
            browserSupportFlag = true;
            navigator.geolocation.getCurrentPosition(function(position) {
                <portlet:namespace />initialLocation = new google.maps.LatLng(
                        position.coords.latitude, position.coords.longitude);
                contentString = "Location found using W3C standard";
                <portlet:namespace />map
                        .setCenter(<portlet:namespace />initialLocation);
                var marker = new google.maps.Marker({
                    map : <portlet:namespace />map,
                    position : <portlet:namespace />initialLocation
            }, function() {
                <portlet:namespace />handleNoGeolocation(browserSupportFlag);
        } else if (google.gears) {
            // Try Google Gears Geolocation
            browserSupportFlag = true;

            var geo = google.gears.factory.create('beta.geolocation');
            geo.getCurrentPosition(function(position) {
                <portlet:namespace />initialLocation = new google.maps.LatLng(
                        position.latitude, position.longitude);
                contentString = "Location found using Google Gears";
                <portlet:namespace />map.setCenter(<portlet:namespace />initialLocation);
                <portlet:namespace />infowindow.setContent(contentString);
                <portlet:namespace />infowindow.setPosition(<portlet:namespace />initialLocation);
                <portlet:namespace />infowindow.open(<portlet:namespace />map);
            }, function() {
                <portlet:namespace />handleNoGeolocation(browserSupportFlag);
        } else {
            // Browser doesn't support Geolocation
            browserSupportFlag = false;
            <portlet:namespace />handleNoGeolocation(browserSupportFlag);

        //add listener for directions change
            <portlet:namespace />directionsDisplay,
            function() {
                var leg = <portlet:namespace />directionsDisplay.directions.routes[0].legs[0];
                Liferay.fire('directionsChanged', {
                        origin : leg.start_address,
                        destination : leg.end_address

    function <portlet:namespace />handleNoGeolocation(errorFlag) {
        if (errorFlag == true) {
            <portlet:namespace />initialLocation = newyork;
            contentString = "Error: The Geolocation service failed.";
        } else {
            <portlet:namespace />initialLocation = siberia;
            contentString = "Error: Your browser doesn't support geolocation. Are you in Siberia?";
        <portlet:namespace />map.setCenter(<portlet:namespace />initialLocation);
        <portlet:namespace />infowindow.setContent(contentString);
        <portlet:namespace />infowindow.setPosition(<portlet:namespace />initialLocation);
        <portlet:namespace />infowindow.open(<portlet:namespace />map);
    function <portlet:namespace />loadScript() {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=<portlet:namespace />initialize";

    window.onload = <portlet:namespace />loadScript;

    function <portlet:namespace />showDirection(source, destination) {
        var request = {
            origin : source,
            destination : destination,
            travelMode : google.maps.DirectionsTravelMode.DRIVING
        <portlet:namespace />directionsService.route(request, function(
                response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                <portlet:namespace />directionsDisplay.setDirections(response);

    Liferay.on('planTravel', function(event) {
        <portlet:namespace />showDirection(event.origin, event.destination);

<div id="map_canvas"></div>

The Google Maps API requires a single div element with an id in the html page to be rendered. Here, we have given the id as 'map_canvas'. The loadScript() method dynamically loads the maps script file. This speeds up the page display. The initialize() method loads the map view with pre-configured values. Also, latest versions of most browsers support geolocation. Geolocation allows tracking user's current location. This information is used to load the map with user's current location.
Note the listener for the directions changed event from the map in the initialize function. When the directions changed event occurs, we republish the event using Liferay's event manager to notify other portlets. Other portlets receives this event to update their display. We saw this in the search form in the first part of this blog series.
To use the two portlets that we have developed so far, type in the names of cities in the origin and destination and hit the Search button. The road rout between the two cities will be shown in the Google map. Now, try changing the cities by dragging the marker in the map. The cities' names are updated in the Plan Your Travel portlet. We will see interesting applications of this event model in the next few portlets.
For more details working on the Google Maps API, see this and this.