Friday, December 31, 2010

jQuery custom animation

jQuery and animation

The most common type of dynamic effect we'll want to perform is the simple show or hide element(s). This is all fine, but jQuery is capable of more complex type animations. In this tutorial we will create more complex (but in essence simple) animation that will show you common usage of animate() jQuery method.

I like to provide complete runnable example for completeness reason, so you can download it from my google code repository.

Basic animations

Before we start we will quickly show common jQuery animation method and their usage. The methods for showing and hiding elements are show() and hide. Using this methods, jQuery change HTML elements style.display property.

We use this methods like so:

$("h1").hide(); //This will hide all h1 elements.
  $("h1").show(); //This will show all h1 elements.

Simple as that! Also jQuery support toggling the display state of elements between revealed and hidden by providing us toggle method.

$("div").toggle(); 

There is bit more to these methods than simple show/hide. When called with no parameters, these methods effect a simple manipulation of the display state of the wrapped elements. But when passed parameters, these effects can be animated so that the changes in display status of the affected elements take place over a period of time.

For example for following code:

$("h1").hide("slow");

will specify the duration of the effect and element will fade out slow. We can also use integer values here (these represent milliseconds). There are also predefined methods for this kind of fade in fade out effects: fadeIn(), fadeOut(), fadeTo(). We can use also slideDown(), slideUp() methods for gradually decreasing vertical size of element and thus remove it from display.

jQuery complex animation

Number of core effect method coming with jQuery is small. This should not be considered as jQuery handicap, because using jQuery animate() method writing our own animation is quite simple if you have rudimentary knowledge of CSS.

jQuery animate(properties, duration) method applies an animation as specified by properties. These properties are object hash that specifies the values that supported CSS style should reach at the end of the animation. The animation takes place by adjusting the values of the style properties from current value for element to the value for an element to the value specified in this object hash. duration optionally specifies the duration of the effect (same as in other simple methods).

Let see example:

$(function() {
   $("img[alt='arrow']").click(function(event) {
      var ball = $(this);                    
      var SCALE = 3;
      ball.animate(
      {                       
        opacity: 'hide',
        width: ball.width()* SCALE,
        height: ball.height() * SCALE
      },
      'fast');
       ball.animate({ opacity : 'show'}, 'fast');
       ball.animate({ top : '+=300'}, 4000);
       ball.animate({ left : '+=600'}, 4000);
       ball.animate({ top : '-=300'}, 4000);
       ball.animate(
       {
         left : '-=600',
         width: '80px',
         height: '80px'
       },
       4000);
   });
});

This example is simple to follow:
We have single image element in our DOM and we first (after user click on in) grab it's instance and named it "ball", then we hide use animate method (lines 5-10) to scale it by factor of 3 and fade it out. Then we show it (line 12), this will cause additional effect (some kind of blinking). Then we move ball into square (lines 13-22) and in the end we will revert ball's size in the same time we move it (lines 16-22).
You can see that we also use integer value for animation duration.

This is no complete tutorial and this animations method can be additionally configured by passing more parameters (like callback functions) and easing function (for animate method), but for this short example this was not necessary.

Here is ball animation in action:


Friday, December 24, 2010

Creating complete jQuery plugin

Introduction

jQuery promote writing reusable components as jQuery plugins. This is good practice and a smart way of working. Also jQuery promotes a certain style for writing these plugins. This short example is simple guideline that show how to do this.

Example

You can download simple example (that include complete Java web application and jQuery plugin that uses Ajax) from my google code repository.

This example is composed of single JSP page that show programming languages names and by clicking on some language we get description of that language in the bottom of page by pulling it from server using Ajax.


1.Naming conventions.

The recommendation is simple: prefix the file name with jQuery, then follow that with the name of the plugin, optionally include version number of the plugin, conclude it with .js.

We named our plugin "details" (because it show details about some programming language, I know it's stupid...but what can you do! :) ) and we named file jquery.cwp.details.js. Here we added unique plugin name to our self (cwp stands for "coding with passion") and limiting name conflict problems.

Similar consideration need to be taken with the names we give to our function. In our case we did not bother with that because there is 100% chance that this plugin will be used by me and only me and I probably will never use it again (outside of this example)...so there you go.

2.Handle $ alias properly.

We have no way of knowing weather a web developer (using out plugin) use $.noConfilct() function to allow the $ to be used by another library, so we need to guard ourself for such situation. We can use following trick to do so:

(function($) {
  //plugin impl.
  })(jQuery);

By passing jQuery to a function that defines the parameters as $, $ is guaranteed to reference jQuery within the body of the function.

3.Complex parameter list.

Most plugins tend to be simple affairs that require few, if any, parameters. Intelligent defaults are supplied when optional parameters are omitted. The bind method is a good example; it the optional parameters are omitted, the listener function, which is normally specified as the third parameter can be supplied as the second.

We can use handy $.extend function to merge default parameter with optional. Consider the following show example:

function complex(p1, options) {
  var settings = $.extend({
    option1 : defaultVal1,
    option2 : defaultVal2,
    option3 : defaultVal3
  }, options||{});
  //"meat" of the function.
}

By merging the values passed by the web developer in the options parameter with an object containing all the available options with their default values, settings variable ends up with the default values superseded by any explicit values specified by the developer.

Note: With options||{} we guard ourself against options object that is null. or undefined.

4.Wrapper methods.

The true power of jQuery in the ability to easily and quickly select and operate on DOM elements. Luckily, we can extend that power by adding wrapper methods of our own. The general pattern of doing so is:

$.fn.functionName = function(params){function-impl};

That is almost it, just remember to always return (this) for chaining support. All that said, here is our function in all its glory :) :

(function($) {
    $.fn.details = function(url, options) {
        var settings = $.extend({
            customClass: null,
            paramName: 'language',
            url: url
        }, options||{});
        this.click(function(event) {
            $('div.details').remove();
            //substitute lt with appropriate start tag and gt with end tag...
            $('lt div gt')
            .addClass('details' +
                (settings.customClass ? (' ') + settings.customClass : ''))
            .css({
                display: 'none'
            })
            .appendTo('body')
            .load(settings.url,
                encodeURIComponent(settings.paramName) + '=' +
                encodeURIComponent($(event.target).text()),
                function() {
                    $(this).closest('.details').fadeIn('slow');
                });
        })
        this.addClass('details');
        return this;
    };
})(jQuery);

Transform XML into HTML using XSLT

Introduction

XSLT stands for Extensible Stylesheet Language for Transformations. As you can see, there is no XML in name, and that is just strange if you
think about it, because XSLT is used for XML document transformation (transform input XML document into output (no necessary XML) document).
One of the advantage of parsing and handling XML documents with XSLT is that XSLT is W3C recommendation (so you have standard tool set and
concepts that are transferable).

Please download example from my google code repository:

XSLT: download
XML example file: download

Concepts

XSLT language should be based on pattern matching. Most of your stylesheet consist of rules (called templates) used to transform
XML documents. Each rule says, "When you see part of a document that look like this (when you see specific tag in XML document), here's how you convert
it into something else.". XSLT is heavily influenced by the design of functional programming languages (Lisp, Scheme, F#, Haskel, ...).

You can think of templates as equivalent to functions in functional languages. In XSLT you do everything with recursion, as in any other F. language.

In oder to follow this tutorial, you need to understand what XML is all about. It is (XML) basically document that holds data and describe meaning of data. You can
describe data by defining schema's (similar to database schema's...).

When we create XML stylesheets we use two standards: XSLT and XPath. You can see my short XPath tutorial if you are not familiar with
this standard. There is also XQuery that is more similar to SQL, but we will not use it here.

There are number of free XSLT processors (Xalan, Saxon, Microsoft XSLT Processor, Altova XSLT Engine). We will use Altova XSLT Engine that is used
in their program XML Spy.

Example

This tutorial will show how to transform XML to HTML file. We will use XML files from
US National Weather Service


They already include XSLT in their XML files, so you need to remove that file name and assign XSL file we will create here.

We will transform weather XML file in rather simple HTML file.

Here's how XML file look like:


You can see that this XML file is quite simple. Only one root element and bunch of child elements.

From this XML file we will create HTML page that looks like this:


You can see that page is also pretty simple. Only subset of elements are shown.

XSLT file for this page looks like this:


As you can see we are using XSLT 1.0 for browser compatibility reasons.

Line-by-line review:
4-6: We match root of the element and then apply templates for all other child elements.
8-17: Create HTML HEAD element and fill some styles.
18: Start BODY element filling.
20 and 24: Set some DIV's (not important)
21: Construct img element by combining two elements from XML.
25: We will not show all elements, we are interested only in "location", "observation_time", "pressure_string" and "wind_string".
30-34: For temperature element we will use special template.
35-37: For all other elements we will use same template. In this template we
use another template for extracting sensible name from XML element tag names (why not use it if they are mostly ok).
38-52: If element tag name contains "string" string then we will remove it. If element tag name contains only '_' char, then replace that char with space ' '. If this is not the case, then just return tag name. In this way we can use single template for processing all elements.

Ok that's it! Let's move on another tutorial...

Thursday, December 16, 2010

Recursion in XSLT

Introduction

I like recursion! It is pure and formal. When you solve problems using recursion you code look cleaner & leaner & meaner! But problem with recursion is that
it is hard to imagine it. You can easily imagine how for loop works, but when you solve complex artificial intelligence algorithms using trees it can get
quite complex and error prone (min-max algorithms for example). I myself like to use recursion only when it might provide substantially more elegant
solution that other methods, and make recursion flow as easy to follow as possible (refactor it to special method,...).

That's all great, but in XSLT (like in any functional language) we are forced to use recursion in situations when we need create functions (templates)
that are not included in XSLT 2.0/1.0 spec. Also using recursion in XSLT is natural way of traversing XML (or any other tree like structured document).

To work with recursion in XSLT, you need to be familiar with couple of things in XSLT. First are off course templates. Templates are analog (or
at least similar) to functions in functional language (Scheme, LISP, F#,...). They have can have parameters and variables. Variables in XSLT are immutable
(they state cannot be changed after first value assignment). For example String object in Java is also immutable. Templates can call itself for recursive calls.
There are no loops in XSLT (don't try to find them). There is xls:forEach but it behave different than loops in imperative language.

Second thing is XPath. XPath is a syntax used to describe parts of XML document. XPath is designed to be used inside an attribute in XML
document. The syntax is a mix of basic programming language expressions and Unix-like path expression.

Example

To show how process XML document using XSLT and recursion we will use example XML document. This document describes F1 2010 season overview for four races.
It shows name of grand Prix (race), data of race, winning driver name, winning team name, no of laps, winning time.


 
  Bahrain
  14/03/2010
  Fernando Alonso
  Ferrari
  49
  
 
 
  Australia
  28/03/2010
  Jenson Button
  McLaren-Mercedes
  58
  
 
 
  Malaysia
  04/04/2010
  Sebastian Vettel
  RBR-Renault
  56
  
 
 
  China
  18/04/2010
  Jenson Button
  McLaren-Mercedes
  56
  
 


We will transform this XML document into another document. The customer want to have data within same XML element (tag) put into single XML element
separated by comma. It is maybe strange request, but it is constructed like that to show how recursion is used in XSLT.

Example of transformated XML:

 Bahrain, Australia, Malaysia, China
 14/03/2010, 28/03/2010, 04/04/2010, 18/04/2010
 ...
 1:39:20.396, 1:33:36.531, 1:33:48.412, 1:46:42.163


Solution:

You can download full file from my google code repository. Here I will attach image:


Recursion start at line 34. Here we create template with two parameters. First parameter is sequence (in XPath 2.0) or node-set (in XPath 1.0) of values we are going to traverse and concatenate with delimiter. Second parameter is resulting string that is printed at the end of template (line: 48) (at the end of recursion).
38 check if recursion should stop. It stops if there are no values left (or there was no values at first place) in sequence.
If sequence is not empty, then we go into recursion and call template (line: 40) again with following parameters:
41: Rest of values in sequence (everything after the first item -- position() > 1).
42: Concatenate first value from sequence into resulting string (we only handle first value differently).

Finite!

Monday, December 13, 2010

Ajax tutorial with jQuery

Introduction

AJAX is just simple technique for refreshing browser DOM with data acquired from some kind of server (Servlet/JSP, PHP, ASP.NET, ...). There is nothing specially clever in this technique.

Ajax is a less recent addition to the web toolbox than many people may realize. In 1998, Microsoft introduced the ability to perform asynchronous request as an ActiveX control (part of Outlook Web Access ).

After few years MS browser introduced standardized XMLHttpRequest (those days everything was flavored with XML :) ) object. These days you will not use XML with AJAX requests (rather JSON, or simple HTML). Google coined the term AJAX (Asynchronous JavaScript and XML -- you see!) and rest is history.

You can download example from this tutorial from my google app code SVN repository.

Plain JavaScript VS jQuery

Using plain JavaScript to implement AJAX (all cross browser JavaScript stuff) is not so easy. In a perfect world, code written for one browser would work in all commonly used browsers. But we do not live in perfect world and in this situation IE is one browser that handle AJAX in different way. The main problem is to create and instance of XMLHttpReauest object.

Let I give you some quick insight what you need to do in other to (just) get instance of this object in plain (cross browser) JavaScript:

var xhr;
if (window.ActiveXObject) {
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
else  if (window.XMLHttpRequest) {
  xhr = new XMLHttpRequest();
}
else {
  throw new Error("This browser is not ajax enabled.");
}

There are couple of things you need to consider when you handle AJAX using plain JavaScript. One is encoding, another is creating handler for response...and so on.

Now, the jQuery code for AJAX request and getting response is as follows:

$('#driverSelectionControl').load('/AjaxExampleCWP/actions/driversList.jsp');

I think we have a winner! So we will be using jQuery from now on and leveraging it great capabilities.

jQuery load() method

Perhaps the most common uses of Ajax is to grab a chunk of content from the server and stuff it into the DOM as some strategic location. jQuery do just that, it's "load" html code into wrapper set using (go figure!) load() method. It sound simple and it is simple!

Let's go straight to the example:

We have page select component with F1 race drivers names filled in. When you change driver name, his details will be pulled from server and appended to DOM without page refresh. Interesting detail in this example is that select HTML component is also populated using Ajax.

Code for initial page DOM:


Now I will show you code for Ajax stuff and explain afterwards.

$(function() {
  $('#driverSelectionControl').load('/AjaxExampleCWP/actions/driversList.jsp');

    $('#driverSelectionControl').change(function(event) {
      $('#driverDetailPanel').
        load('/AjaxExampleCWP/actions/driversDetails.jsp',
             {driverId : $(event.target).val()});
    });
});

02: Loading options html components into select component. You see how easy is to use Ajax with jQuery! :) We just need to give URL to JSP page.

Here is JSP page for driver list:






That's it. All that this JSP page do is rendering options components.

04-08(from previous example): Here we handle change event. When user select another driver (value is changed), then we load his detail from driversDetails.jsp. We pick user by passing parameter (driverId) to JSP page.

Here what JSP page look like:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


    
        
        
        
        
        
    
    
        
        
        
        
        
    
    
        
        
        
        
        
    


Driver name ${item.name}
Team name ${item.team}
Podiums ${item.podiums}
Points ${item.points}
Date of Birth ${item.birth}

You can use POST (default) or GET HTTP request method using load method. If you want to use POST (like in this example) then you send object hash as parameter to load (for example: {driverId : 205} ). If you want to initialize GET request, then you need to pass query string. If you use GET, you must ensure that your string is properly formated (names and values are URI-encoded).

If you are wondering when to use POST and when to use GET then follow this recommendations:

Use GET request when request operation that is made again and again make no change to state of server (for example when you just pulling data from server). This mean that our example is in opposite to this recommendation!
Use POST request when operation your request is initiating is non-idempotent (as opposite to idempotent like in GET). This mean, that you should use POST when you change some state on server (changing, or updating the data).

Other jQuery Ajax methods

jQuery include other methods for Ajax functionality like $.get(), $.post() for explicit GET or POST request operations.

jQuery also provides a general utility function for making Ajax requests, named $.ajax(). Under the covers, all other jQuery features uses this function. It it quite powerfull, but also complex. Feel free to investigate this function if you are interested.

Monday, November 22, 2010

Converting Java List (or any Java collection) to Array

There are many times when you need to create dynamic data structure that hold data and then convert it into array.

Collection interface posses method T[] toArray(T[] a). We can use this method to convert our list or other collection into array.

By default toArray method provide service of returning of Object array (Object[]). If this is not what we want and we knows type of the array, then we can provide our type and avoid explicit converting.

To do that, we need to provide array type and instance of that array type like so:

List list = new ArrayList();
String[] stringList = (String[])list.toArray(new String[list.size()]);

Please see details in Java API

Saturday, November 20, 2010

Dynamically loading new script into page using jQuery

We mostly load external script files in our page using script src tag. But now and then, we need to load JavaScript file under script control. There are couple of use cases for this:


  • We don't to load file at runtime (because of some restriction, or because of file size);
  • or maybe we need to execute some condition before decide which file we will load.
jQuery provide <b>$.getScript()</b> utility function to enable this functionality. This function uses jQuery Ajax functions to fetch this file. 

Ok, let's see how it works!


Following code represent external JavaScript file (named: new_script.js).
$('#console').html("Script is loaded...");
function dragonBallFunction(value) {
    alert(value);
}

On page we have defined two buttons. First button load script file, second execute function from external file that first loaded.

As you can see it is quite simple:

$(function() {
    $('#loadButton').click(function() {
        $.getScript("new_script.js");
    });
    $("#executeButton").click(function() {
        dragonBallFunction('Piccolo is not saiyan!\n::Goku:: is!');
    });
});

//normal html stuff 


Monday, November 15, 2010

Oracle ADF - Debug view object query with parameters

Introduction

Slow and huge non optimized select queries are one of the main problem when developing ADF application.
To track SQL performance (and other) issues, we need to be able to see select queries that we send to database.

Solution

View object performance issues are mainly connected with execution of executeQueryForCollection method that fill
VO with rows from database.

If you want to track all VO queries that return collections you need to overwrite executeQueryForCollection in view
object implementation. The best practices is to have one global ViewObjectImpl that is at the to of the View Object hierarchy (that will all View Object extend).

So to see queries, you need to write following in VO implementation class:

public void executeQueryForCollection(Object rowset, Object[] params,
                                          int noUserParams) {        
        System.out.println("VO name: " + this.getFullName());
        System.out.println("Query is: " + this.getQuery());
        super.executeQueryForCollection(rowset, params, noUserParams);        
    }

You can freely use any debug tool you like (Log4J for example), I just use java's System.out for convenient reason.

If we try to test this method we will see that ADF write only parameters names (:vc_temp1, :vc_temp2 or something like this)
and parameters values are missing.

To see values, wee need to read second parameters of executeQueryForCollection method. This parameter is filled by framework
and it contain pairs (name, value) of parameters. It is kind of strange (to use array of object of array of objects -- Object[][])
for parameters saving if you ask me, but there must be a reason. :) We will read it with following method:

private void getParametersValues(Object[] params) {
      if (getBindingStyle() == SQLBuilder.BINDING_STYLE_ORACLE_NAME) {
        if (params != null) {
          for (Object param : params) {
            Object[] value = (Object[])param;
            System.out.println("Name=" + value[0] + "; Value=" + value[1]);
          }
        }
      }      
    }

You just need to insert this method into executeQueryForCollection and you have full query monitoring from you JDeveloper console:

public void executeQueryForCollection(Object rowset, Object[] params,
                                          int noUserParams) {        
        System.out.println("VO name: " + this.getFullName());
        System.out.println("Query is: " + this.getQuery());
        getParametersValues(params);
        super.executeQueryForCollection(rowset, params, noUserParams);        
    }

Wednesday, November 10, 2010

Niklaus Wirth

I first heard of Niklaus Wirth name during my freshmen years at college. I didn't know who he is, but my professor keep repeating his name in correlation to MODULA-2 language that we used in our classes. At first I did't like MODULA-2 language because it look very simple and well not very modern language (then it was all about C++ and Java). But as time pass, I realize that simplicity of this language and shortage of libraries  (as compare to Java for instance) is really beneficiary because it did't divert our attention to less important stuff. Off course most people will recognize Wirth as father of PASCAL language.

Name of Niklaus Wirth can also be connected to programming languages as: Euler, PASCAL, Algol, Oberon, PL/0.  Also Oracle's PL/SQL is very similar to MODULA-2 and Oberon for example. You can learn more about him at wikipedia.

I have recently watched interview with him on you tube and  I want to repeat most important and useful notes from this video. You can really recognize how he really understand problems of old and modern programming languages and programming concepts and gives some solution to this issues.

Video is separated into 3 parts, but first part is deleted or something, so here are only second and third part. I decide to do overviews of these videos because I really think that there good and useful observations that I want to repeat.

Second (first) video is not so interesting in concepts insights, but it is more interesting for historic overview of PASCAL language.

In third (second) video Wirth talks about gap between real hardware and high level language (like Java, C#) and how compilers need to bridge this gap in between. He say that because this gap is getting wider, it is more difficult to bridge this gap.

Also he say that hardware people are only looking for more speed and they are not taking software aspects into consideration and thus making programmers life more difficult. Here he is talking about difficulties that new hardware is creating for compilers and because of that new compiles are more complex and they really should't be if you think about it. They should be simpler and simpler as we create more complex CPUs.


The most interesting part of this interview is when he start talking about programs verification. He define program verification like exercise if formalism and say that you can make verification using only basics language axioms and derivations rules that are in heart of definition of language. This is really what it is all about if you ask me: clear formal programs and programming concepts. He say that we need formal and precise ambiguously defined languages for this (language based of clear rules and without access to any hardware stuff - hint any pointer language does not belong to this group, OBERON does).
He stated that Java is beautiful language, but it is long and lengthy and unnecessary complicated. And if you design language in some Ad hoc way and think that compiler will deal all difficulties, then you cannot have good language (C++ anyone? :) ).
He say that using languages that are not clear and formal lead to more necessary complexities and disasters. He criticized universities because they only buy software from companies and do not create new values and ideas any more.

Also as final statement he say that modern systems (and current programmers) are challenging many difficulties because they need to use libraries which do not have properly specified interfaces and many work goes to linking our program with this libraries. This leads to buggy programs and debugging as he stated is not science and not even engineering but only try-error principle.

You can also find great qoutes on wiki from this great scientist and engineer.

Also please read his book about Algorithms and Data Structures. This book was holy grail at our university (translated to our native language) and if you read it, it will teach you basic principles of good programming (algorithms + data structures = program).

Thursday, November 4, 2010

Design Patterns in Java - Abstract Factory and Factory Method

Introduction

These factory design patterns belong to group of patterns that are named "creational". These patterns helps in instantiation of classes. So with this pattern we separate creation process from object usage (If you think about if creation of new classes is kind of low level stuff like allocating memory for pointer...I now that it is not...but I just give a small analogy...whatever). So the name "factory" is derived from "factory of objects". In this way we do not use "new" keyword in object creation, but we use this pattern. With this pattern we choose which concrete class we will use at runtime and also in this way we can introduce new classes in our code without changing our base code.

This is all common sense to me (plain polymorphism in use...nothing more), and remember: Always program to interface not concrete class (don't you forget this!).

I will show same example for both patterns. In this example we need to decorate string text with some special characters. Nothing fancy...for example: from "decorate me" we will have "** decorate me **". So we just put two stars at end and beginning. All my examples are simple, because I want to concentrate at topic and at current problem.

Factory method

/**
 * Simple example of Factory Method pattern.
 * @author jan.krizan
 */
interface Decorator {

    String doDecorating(String str);
}

class StarDecorator implements Decorator {

    public String doDecorating(String str) {
        return "** " + str + " **";
    }
}

class OtherDecorator implements Decorator {

    public String doDecorating(String str) {
        return "<<|-- " + str + " --|>>";
    }
}

public class Factory {

    public static final int STAR_DECORATOR = 1;
    public static final int OTHER_DECORATOR = 2;

    public static Decorator createSpecificDecorator(int i) {
        if (i == STAR_DECORATOR) {
            return new StarDecorator();
        } else if (i == OTHER_DECORATOR) {
            return new OtherDecorator();
        } else {
            return null;
        }
    }

    public static void main(String[] args) {

        String nonDecoratet = "Please decorate me!";

        Decorator decorator = createSpecificDecorator(STAR_DECORATOR);

        System.out.println(decorator.doDecorating(nonDecoratet));
    }
}
Output of this example is: "** Please decorate me! **". No kidding...really! :) Ok, never mind that, let's comment it!:
(5 - 8) We first create interface.
(10 - 15 and (17 - 22) Then we implement that interface.
As you can see all straight forward for now.
(29 - 37) This represent factory that will choose (base on input parameter) which
class to instantiate.
Then we test the stuff in main.

Abstract factory

Abstract factory is (as you can figure out from its name) in higher level at higher level of abstraction. In abstract factory event the factory is abstract (interface or abstract class) and we choose factory at runtime (not the "working" class). The factory will "know" which class it need to instantiate in order to fulfill job in hand.

/**
 *
 * Simple example of Abstract Factory pattern.
 * @author jan.krizan
 */
interface DecoratorFactory {

    Decorator createDecorator();
}

class StarDecoratorFactory implements DecoratorFactory {

    public Decorator createDecorator() {
        return new StarDecorator();
    }
}

class OtherDecoratorFactory implements DecoratorFactory {

    public Decorator createDecorator() {
        return new OtherDecorator();
    }
}

interface Decorator {

    String doDecorating(String str);
}

class StarDecorator implements Decorator {

    public String doDecorating(String str) {
        return "** " + str + " **";
    }
}

class OtherDecorator implements Decorator {

    public String doDecorating(String str) {
        return "<<|-- " + str + " --|>>";
    }
}

public class Factory {

    public static final int STAR_DECORATOR = 1;
    public static final int OTHER_DECORATOR = 2;

    public static DecoratorFactory createSpecificDecorator(int i) {
        if (i == STAR_DECORATOR) {
            return new StarDecoratorFactory();
        } else if (i == OTHER_DECORATOR) {
            return new OtherDecoratorFactory();
        } else {
            return null;
        }
    }

    public static void main(String[] args) {

        String nonDecoratet = "Please decorate me!";

        DecoratorFactory decoratorFac = createSpecificDecorator(OTHER_DECORATOR);

        Decorator decorator = decoratorFac.createDecorator();

        System.out.println(decorator.doDecorating(nonDecoratet));
    }
}

Here we see that code is almost same as for Factory Method. There are just small but important differences:
(11 - 16 and 18 - 23) Here we create another layer, this seem like waste of code, but this can be beneficiary if for example we have more than one method to implement and we don't want all method to implement (just subset). In this way we in our concrete classes implement only those method we need for our work and ignore other. We can extends one interfaces to accomplish this. If this sound a little bit confusing for you, don't worry and search some good example of Abstract Factory and you will see what I talking about. For example here.

Creating class instances is similar and also testing is similar, we just have another step and that is to obtain Decorator class through createDecorator method.

Using Abstract Factory pattern for simple example like this is stupid and overkill, but I want to show differences between the two patterns.

You can download code for this two examples from here.

Sunday, October 31, 2010

Spring framework - beans

Introduction

As we all know Spring framework represent standard in Java application development. It can be used in desktop application or on web apps. It can help us with database access, security, RMI, web layer (MVC) and it can also integrate with other technologies like cutting edge GWT, or little bit older Flex stuff. There is also great Roo stuff (GWT or flex front-end)...but I don't know is this technology mature enough.

Spring framework secret lies in its simplicity, small footprint, ability to test outside of container.

In this article we will become more familiar with framework essential stuff -- wiring and instantiating Java POJO classes (Beans).

Source for following examples can be downloaded from my google code repository.

Spring wiring

In Spring, components (mainly Java classes...nothing fancy like CORBA or DCOM don't worry) are not responsible for managing their associations with other components, instead, references are passed through container. Controlling associations between components (passing reference from one place to another) is know an wiring. And this is at heard of Spring philosophy. This components are called beans and they share similarities with Java beans. And all this philosophy started with one of the greatest book in Java ecosystem: Expert One-on-One J2EE Design and Development.

Spring also act as bean factory (see my blog post about factory pattern that is here). But unlike many implementations of factory pattern, which often can create only single type of object, spring bean factory can create many different types of beans (list, data sources,...as you will see).

Off course, container is at the core of the Spring framework. This container uses inversion of o control (please see my post about template method design pattern that follows this principle, also known as Hollywood principle - "Don't call us, we will call you!") to manage component associations. There are several Spring containers and we will use Applicationcontext container that is most widely used and provide most basic Spring features we will explore in this post.

I choose to use simple Java application and not web app, because there are already many different examples of using Spring in web application and in this way we can avoid additional configurations and complexities that comes with web apps. For testing we will not use JUnit, but simple "public static void main".

In our simple Java application we will use Spring 2.5.6 (because it is lightweight -- 1.2MB with only essential libraries, and because I want to integrate it to Google App Engine at some point), we will also use XML file for bean wiring and defining. I don't like annotations because they mix with my code and break apart non-intrusive concept. I don't shy away from XML, because I think XML is not evil if you use it in right situations (like this one).

I will not go into details with Spring framework (like life cycle of bean), but I will just show main Spring futures on example (this will be enough to learn basic concepts). So let's start!

Example introduction

We will implement simple Employee (n)<->(1) Department system. This system can (beside classic CRUD operations) find largest department (department with largest number of employees), assign employee to that department and remove employee from department...and that's that!

Example service layer

First we will implement service layer of our example application. This is because service layer is on the top of abstraction hierarchy. In service layer we define operations we want our application to support.

There are two service components in service layer defined by interfaces (it is important to program to interface not implementation!): employee and department service. Employee service handles following employee matters (it's basically simple CRUD):

public interface EmployeeService {

    Employee findEmployee(int employeeId);

    void removeEmployee(int employeeId);

    List getAllEmployees();
    
    void createNewEmployee(Employee employee);

}

Department service can provide following operations (services):

public interface DepartmentService {
   
    Department findDepartment(int departmentId);
    
    void createNewDepartment(Department department);

    void removeDepartment(int departmentId);
    
    List getAllDepartments();
   
    /**
     * Find department with largest number of employees.
     * @return
     */
    Department findLargestDepartment();

    /**
     * Assign employee into department.
     * @param employee
     * @param department
     */
    void assign(Employee employee, Department department);
    
    /**
     * Remove employee from department.
     * @param employeeId
     * @param departmentId
     */
    void remove(int employeeId, int departmentId);

}

As you can see Department service provide couple of more complex operations than simple CRUD.

We have two classes that implement these two service interfaces:

Employee service concrete implementation:

public class EmployeeServiceImpl implements EmployeeService {

    private EmployeeDao employeeDao;

    public Employee findEmployee(int employeeId) {
        return getEmployeeDao().findById(employeeId);
    }

    public void createNewEmployee(Employee employee) {
        getEmployeeDao().create(employee);
    }

    public void removeEmployee(int employeeId) {
        Employee deleteEmployee = getEmployeeDao().findById(employeeId);
        getEmployeeDao().delete(deleteEmployee);
    }

    public List getAllEmployees() {
        return getEmployeeDao().retrieveAll();
    }

    public EmployeeDao getEmployeeDao() {
        return employeeDao;
    }
    
    public void setEmployeeDao(EmployeeDao employeeDao) {
        this.employeeDao = employeeDao;
    }   

Department service concrete implementation:

public class DepartmentServiceImpl implements DepartmentService {

    private DepartmentDao departmentDao;
    private EmployeeService employeeService;

    public Department findDepartment(int departmentId) {
        return getDepartmentDao().findById(departmentId);
    }

    public void createNewDepartment(Department department) {
        getDepartmentDao().create(department);
    }

    public List getAllDepartments() {
        return getDepartmentDao().retrieveAll();
    }

    public Department findLargestDepartment() {
        Department largestDepartment = getAllDepartments().size() > 0 ? getAllDepartments().get(0) : null;

        for (Department dep : getAllDepartments()) {

            if (dep.getEmployees().size() > largestDepartment.getEmployees().size()) {
                largestDepartment = dep;
            }
        }

        return largestDepartment;
    }

    public void removeDepartment(int departmentId) {
        Department deleteDepartment = findDepartment(departmentId);
        getDepartmentDao().delete(deleteDepartment);
    }

    public void assign(Employee employee, Department department) {
        if (department.getEmployees().size() < department.getMax()) {                                    
            getEmployeeService().createNewEmployee(employee);
            getDepartmentDao().addEmployee(department, employee);
        }
    }
    
    public void remove(int employeeId, int departmentId) {
       
        Department department = findDepartment(departmentId);
        Employee deleteEmployee = getEmployeeService().findEmployee(employeeId);

        getDepartmentDao().removeEmployee(department, deleteEmployee);
        
        if (department.getEmployees().isEmpty())
            removeDepartment(departmentId);
    }

    public EmployeeService getEmployeeService() {
        return employeeService;
    }

    public void setEmployeeService(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    public DepartmentDao getDepartmentDao() {
        return departmentDao;
    }
    
    public void setDepartmentDao(DepartmentDao departmentDao) {
        this.departmentDao = departmentDao;
    }
    
}
There is no much stuff going on here (regarding both services - Employee and Departments) , as you can see much of the responsibility is delegated to underlaying DAO (Data Access Object) bean. Data Access Object beans handle interactions with database (or some other type of data storage - flat files for example, vintage databases, ...) to read and write employees and departments informations.

Implementation of these beans are not important for understanding Spring basic, so I will omit them (you can see implementation from downloadable example if you are curious). Let just say that implementation of these DAO beans in this example is very simple and it uses only java.util.List to hold data. You will see how we initially fill this list using Spring. So no persistence logic is implemented.

As you can see we both EmployeeServiceImpl and DepartmentServiceImpl can be given a reference to its DAO bean through "set" (setEmployeeDao and setDepartmentDao) method. You can also set them through constructor.

Example wiring

We choose XML as strategy for bean wiring. Wiring beans is quite simple. We use "" tags to define one Java Bean (or any Java object, actually -- it not need to be bean) to be configured with the Spring container.

Spring beans are by default singletons, but you can make beans to act like prototypes by setting singleton="false" attribute on bean element.
So we have something like this to define DepartmentService bean (EmployeeService bean is defined in same way):

        
            
        
        
            
        
    
In this simple bean XML wiring, we define bean with id departmentService and point to the full qualify class name (this class is concrete implemented class -- not interface). At this point we added a bean into Spring container (registered it) and now we can do whatever we want with this bean.

Beans can have properties. These properties are nothing more than Java properties. So we map these bean properties into Java properties (in this case) using XML. That is that.

This technique for populating a bean property based on standard naming convention is called dependencies injection. Off course this Java properties need to have matching "get" and "set" method (like in Java beans, or like in JSP/JSF backing beans). And this process is in the core of Spring framework (OK, there is also some other things like Aspect Oriented Programming - AOP, but I will talk about that later).

We can set properties with simple types (like int, long, float, String...) or we can set references to other beans (other Java object of any kind) like in this example (using ref tag). In this way and in our example we give DepartmentServiceImpl a reference to class that implement DepartmentDao interface (ref bean="departmentDao"/>).

Referencing other beans enable us to inject other beans into existing beans and in this way we create references between classes not as part of class logic but in Spring container this help us in leveraging this job to Spring and help us create cleaner and meaner code with ability of changing references only in XML.

We can also wire collections in Spring. In our example we did't use persistence logic or database, we just use simple java.util.List collections to hold data. So we use Spring to inject this data into DAO beans. We set list of departments into Java property named departments that have following type definition: java.util.List. So, we fill up one bean property with list of departments, this list of departments is defined in Spring XML file like so (I will show only one):

        
            1
        
        
            QA
        
        
            2
        
        
            
        
        
            
                
            
        
    
In this way we initially fill up collection that list of Departments.

Spring test

In oder to test Spring you need to do following:
ApplicationContext context = new ClassPathXmlApplicationContext("simpleappcontext.xml");

EmployeeService employeeService = (EmployeeService)context.getBean("employeeService");

DepartmentService departmentService = (DepartmentService)context.getBean("departmentService");

First get instance of context and read bean definition from xml file named "simpleappcontext.xml".
Then just get beans by their names and use them. :)

See my example for detail insight.

Friday, October 15, 2010

Oracle ADF advanced techniques - Dynamically changing query in view object

Introduction

If you have strange requirements then you may need sometimes to dynamically change SQL query where clause in View Object. I have such requirement when customer said that I can not create additional indexes on table. I overcome that problem by dynamically change SQL query where clause (to use indexes that were available).

To use this functionality, you need to override buildWhereClause(StringBuffer sqlBuffer, int noBindVars) method in view object implementation. You use sqlBuffer parameter in this method (which contains SQL query where in StringBuffer) to change SQL in correlation to you needs. Just replace, remove, add string in this parameter. Just remember to use same bind variables names which will be use in VO SQL call (generic bind variables names are named like :vc_temp_1, :vc_temp_2,...).

Ok, here is the code:

@Override
    protected boolean buildWhereClause(StringBuffer sqlBuffer, int noBindVars) {

        //call super and see if there is where clause.
        boolean hasWhereClause = super.buildWhereClause(sqlBuffer, noBindVars);

        if (hasWhereClause) { 
            //modify existing where query.
        }
        else { 
            //or if you add where clause then return true;
            hasWhereClause = false; 

        }

        return hasWhereClause;
    }

Thursday, October 14, 2010

Oracle ADF advanced techniques - Custom view object based on JDBC or Ref Cursor

Introduction

By default view objects read their data from the database and automate the task of working with the JDBC on our behalf. However, if we override specific methods in View Object implementation class, we can create our own mechanism for retrieving data for custom view object. We can use everything from web services, xml files, plain jdbc, or specific database constructions (like cursors in oracle database). So in this example we will show how can you create read-only view object uses cursor as alternative data source. This construction is called "ref cursor". Ok, let's begin!

Initial JDeveloper setup

1. Create Application module. In our case it is application module that have connection to FOD database.

2. Now create read-only view object that select person_id, first_name, last_name (just tree for sanity reason) from person table in FOD scheme. Don't forget to generate view object class (*Impl). Query for view object will be simple:
SELECT person_id, first_name, last_name
  FROM persons
 WHERE first_name LIKE :person_name

And how it look in JDev:


3. Then create Bind Variable with name "person_name".


Test it:



And move on...

Initial database setup

If you intent to use Ref Cursor, you need to create function in pl/sql that return Ref Cursor. we will create following package in FOD scheme.

CREATE OR REPLACE PACKAGE fod_ref_cursor
IS
   TYPE ref_cursor IS REF CURSOR;

   FUNCTION get_person_from_name (f_name VARCHAR2)
      RETURN ref_cursor;
END fod_ref_cursor;
/

SHOW errors

CREATE OR REPLACE PACKAGE BODY fod_ref_cursor
IS
   FUNCTION get_person_from_name (f_name VARCHAR2)
      RETURN ref_cursor
   IS
      the_cursor   ref_cursor;
   BEGIN
      OPEN the_cursor FOR
         SELECT person_id, first_name, last_name
           FROM persons
          WHERE first_name LIKE f_name;

      RETURN the_cursor;
   END get_person_from_name;
END fod_ref_cursor;
/

SHOW errors
You can test Ref cursor in following way:
SET serveroutput on;

DECLARE
   the_cursor     fod_ref_cursor.ref_cursor;
   p_id           persons.person_id%TYPE;
   p_first_name   persons.first_name%TYPE;
   p_last_name    persons.last_name%TYPE;
BEGIN
   the_cursor := fod_ref_cursor.get_person_from_name ('Steven');

   LOOP
      FETCH the_cursor
       INTO p_id, p_first_name, p_last_name;

      EXIT WHEN the_cursor%NOTFOUND;
      DBMS_OUTPUT.put_line (p_id);
   END LOOP;
END;

Customizing framework

Then you need to override some methods from PersonsImpl.java.

(This code bellow is taken from Oracle Fusion advance ADF examples and little bit simplify).

public class PersonImpl extends ViewObjectImpl {

    private static final String FUNCTION_NAME =
        "fod_ref_cursor.get_person_from_name(?)";
    private static final String BIND_VARIABLE_NAME = "person_name";

    private void fillAttributes(ViewRowImpl r,
                                ResultSet rs) throws SQLException {
        populateAttributeForRow(r, 0, rs.getLong(1));
        populateAttributeForRow(r, 1, rs.getString(2));
        populateAttributeForRow(r, 2, rs.getString(3));
    }


    /**
     * This is the default constructor (do not remove).
     */
    public PersonImpl() {
    }

    /**
     * Overridden framework method.
     *
     * Executed when the framework needs to issue the database query for
     * the query collection based on this view object. One view object
     * can produce many related result sets, each potentially the result
     * of different bind variable values. If the rowset in query is involved
     * in a framework-coordinated master/detail viewlink, then the params array
     * will contain one or more framework-supplied bind parameters. If there
     * are any user-supplied bind parameter values, they will *PRECEED* the
     * framework-supplied bind variable values in the params array, and the
     * number of user parameters will be indicated by the value of the
     * numUserParams argument.
     */
    protected void executeQueryForCollection(Object qc, Object[] params,
                                             int numUserParams) {
        storeNewResultSet(qc, retrieveRefCursor(qc, params));
        super.executeQueryForCollection(qc, params, numUserParams);
    }

    /**
     * Overridden framework method.
     *
     * Wipe out all traces of a built-in query for this VO
     */
    protected void create() {
        getViewDef().setQuery(null);
        getViewDef().setSelectClause(null);
        setQuery(null);
    }

    /**
     * Overridden framework method.
     *
     * The role of this method is to "fetch", populate, and return a single row
     * from the datasource by calling createNewRowForCollection() and populating
     * its attributes using populateAttributeForRow().
     */
    protected ViewRowImpl createRowFromResultSet(Object qc, ResultSet rs) {
        /*
     * We ignore the JDBC ResultSet passed by the framework (null anyway) and
     * use the resultset that we've stored in the query-collection-private
     * user data storage
     */
        rs = getResultSet(qc);

        /*
     * Create a new row to populate
     */
        ViewRowImpl r = createNewRowForCollection(qc);

        try {
            /*
       * Populate new row by attribute slot number for current row in Result Set
       */
            fillAttributes(r, rs);
        } catch (SQLException s) {
            throw new JboException(s);
        }
        return r;
    }

    /**
     * Overridden framework method.
     *
     * Return true if the datasource has at least one more record to fetch.
     */
    protected boolean hasNextForCollection(Object qc) {
        ResultSet rs = getResultSet(qc);
        boolean nextOne = false;
        try {
            nextOne = rs.next();
            /*
       * When were at the end of the result set, mark the query collection
       * as "FetchComplete".
       */
            if (!nextOne) {
                setFetchCompleteForCollection(qc, true);
                /*
         * Close the result set, we're done with it
         */
                rs.close();
            }
        } catch (SQLException s) {
            throw new JboException(s);
        }
        return nextOne;
    }

    /**
     * Overridden framework method.
     *
     * The framework gives us a chance to clean up any resources related
     * to the datasource when a query collection is done being used.
     */
    protected void releaseUserDataForCollection(Object qc, Object rs) {
        /*
     * Ignore the ResultSet passed in since we've created our own.
     * Fetch the ResultSet from the User-Data context instead
     */
        ResultSet userDataRS = getResultSet(qc);
        if (userDataRS != null) {
            try {
                userDataRS.close();
            } catch (SQLException s) {
                /* Ignore */
            }
        }
        super.releaseUserDataForCollection(qc, rs);
    }


    /**
     * Return a JDBC ResultSet representing the REF CURSOR return
     * value from our stored package function.
     */
    private ResultSet retrieveRefCursor(Object qc, Object[] params) {
        ResultSet rs =
            (ResultSet)callStoredFunction(OracleTypes.CURSOR, FUNCTION_NAME,
                                          new Object[] { getNamedBindParamValue(BIND_VARIABLE_NAME,
                                                                                params) });
        return rs;
    }

    private Object getNamedBindParamValue(String varName, Object[] params) {
        Object result = null;
        if (getBindingStyle() == SQLBuilder.BINDING_STYLE_ORACLE_NAME) {
            if (params != null) {
                for (Object param : params) {
                    Object[] nameValue = (Object[])param;
                    String name = (String)nameValue[0];
                    if (name.equals(varName)) {
                        return (String)nameValue[1];
                    }
                }
            }
        }
        throw new JboException("No bind variable named '" + varName + "'");
    }

    /**
     * Store a new result set in the query-collection-private user-data context
     */
    private void storeNewResultSet(Object qc, ResultSet rs) {
        ResultSet existingRs = getResultSet(qc);
        // If this query collection is getting reused, close out any previous rowset
        if (existingRs != null) {
            try {
                existingRs.close();
            } catch (SQLException s) {
            }
        }
        setUserDataForCollection(qc, rs);
        hasNextForCollection(qc); // Prime the pump with the first row.
    }

    /**
     * Retrieve the result set wrapper from the query-collection user-data
     */
    private ResultSet getResultSet(Object qc) {
        return (ResultSet)getUserDataForCollection(qc);
    }


    //----------------[ Begin Helper Code ]------------------------------
    public static int NUMBER = Types.NUMERIC;
    public static int DATE = Types.DATE;
    public static int VARCHAR2 = Types.VARCHAR;

    /**
     * Simplifies calling a stored function with bind variables
     *
     * You can use the NUMBER, DATE, and VARCHAR2 constants in this
     * class to indicate the function return type for these three common types,
     * otherwise use one of the JDBC types in the java.sql.Types class.
     *
     * NOTE: If you want to invoke a stored procedure without any bind variables
     * ====  then you can just use the basic getDBTransaction().executeCommand()
     *
     * @param sqlReturnType JDBC datatype constant of function return value
     * @param stmt stored function statement
     * @param bindVars Object array of parameters
     * @return function return value as an Object
     */
    protected Object callStoredFunction(int sqlReturnType, String stmt,
                                        Object[] bindVars) {
        CallableStatement st = null;
        try {
            st =
 getDBTransaction().createCallableStatement("begin ? := " + stmt + "; end;",
                                            0);
            st.registerOutParameter(1, sqlReturnType);
            if (bindVars != null) {
                for (int z = 0; z < bindVars.length; z++) {
                    st.setObject(z + 2, bindVars[z]);
                }
            }
            st.executeUpdate();
            return st.getObject(1);
        } catch (SQLException e) {
            throw new JboException(e);
        }
    }

    /**getEstimatedRowCount - overridden for custom java data source support.
     */
    public long getEstimatedRowCount() {
        long value = super.getEstimatedRowCount();
        return value;
    }


    /**
     * Returns the bind variable value for person_name.
     * @return bind variable value for person_name
     */
    public String getperson_name() {
        return (String)getNamedWhereClauseParam("person_name");
    }

    /**
     * Sets value for bind variable person_name.
     * @param value value to bind as person_name
     */
    public void setperson_name(String value) {
        setNamedWhereClauseParam("person_name", value);
    }
}

You can use this exactly same code, you just need to change FUNCTION_NAME and BIND_VARIABLE_NAME and complete code for fillAttributes method in oder to properly map JDBC result set to View Object attribute set. Simple as that.

As I can see, this kind of data pulling in View Object in some circumstances event speed up data load.

Plain JDBC data pull

If you want to use plain JDBC instead of Cursor, you can do something like this:
protected Object callStoredFunction(int sqlReturnType, String stmt,
                                        Object[] bindVars) {
        PreparedStatement st = null;
        try {
                        
            st = getDBTransaction().createPreparedStatement("SELECT person_id, first_name, last_name\n" + 
            "  FROM persons where person_id = 100", 0);
            
            return st.executeQuery();
        } catch (SQLException e) {
            throw new JboException(e);
        }
    }


Code for this example can be downloaded from here: http://codingwithpassionblog.googlecode.com/files/CustomViewObject.zip

Saturday, October 9, 2010

XPath tutorial for busy programmer

Introduction

As w3.org standard say: XPath is a language for addressing parts of an XML document. Ok...that is simple enough. XPath is just basically a mean to traverse XML document and perform search on it. We can use structure of the XML document (semantics of data), or on data itself to perform that search. We can use XPath in XML transformations (XSLT), in SOA (BPEL language). And as I can see jQuery use similar logic for its selector search operations.

XML document

XPath can query any part of the XML document (any node at any level - XML documents are treated as trees of nodes). As a result of search, XPath may return null, string, number or another XML node (that can also be queried). XPath is used to navigate through elements or attribute of an XML document.

We will use following XML document:


 
  Arcade
  MAME
  true
 
 
  Pocket
  Sony PSP
  false
   
 
  Console
  Nintendo Wii
  true
 
  
  Console
  Sony PS2
  true
 


Basic node selection

To navigate through XML document we are using path expressions. The most to common expressions we will use are slashes : single ("/"), or double ("//").

Single slash will perform search from root node. In our XPath search as: "/game-systems/system/type" will return following result (in XMLSpy):




Double slash will perform traverse through XML tree and find out all nodes that match the selection no matter where they are in XML. So selection: "//type" in our example will produce same result as previous example.



Also common expression path to select XML nodes are: "@, ., ..".

"@" is used to select attribute, as in: "/game-systems/system/emulator/@usable", where we select value of usable attribute in system node.



"." will select current node, and ".." parent node. This is similar like selecting file path in file system!

Selecting parent of emulator node (hint: system): "/game-systems/system/emulator/..".



Finding specific node

To find some specific nodes we use predicates. With this construction we can perform search to find node with specific element or attribute value. Also we can extract specific result from node set result (if there is more that one node as result from previously search). Predicates are always embedded in square brackets.

Finding first system/emulator value can be done with following search:
"/game-systems/system[1]/emulator".

To find all system name with usable emulator we will write:
"/game-systems/system/emulator[@usable='true']/../name" -- here we use ".." as a way to move up to previous element in XML tree.



Finding node-set relative to the current node

We can also use XML tree structure (you know, children, parents and stuff) to find specific nodes.

For example, we can write previous example as follows: "/game-systems/system/emulator[@usable='true']/ancestor::system/name.

This is somewhat longer but it does same thing. Here we are using ancestor function that return ancestor of current element (system in this case). You can also search for child, attributes, descendants and similar searches that you can also perform (in most cases) using basic node selectors and predicates.

Monday, October 4, 2010

Design Patterns in Java - Template Method

Introduction

This is first article about OO design patterns, we will start with the most useful pattern.
Template method (GoF - Gang Of Four) present good example of using concrete inheritance. If you ask me, using inheritance in this way is far more productive than using concrete inheritance for code reuse. Everything you think you can do with concrete inheritance, you can do also with plain object composition. But, ok...never mind about that, let's write something about template method pattern.

You can download example of this Java code from my repository on google code:
https://code.google.com/p/codingwithpassionblog/source/browse/trunk/src/org/codingwithpassion/patterns/templateMethod/DecorateData.java

Usage

This pattern address common problem: we know the steps of an algorithm and the order in which they should be performed, but we don't know (or don't care) how to perform all of the steps. Template method encapsulate individual steps we don't know how to perform to abstract methods in abstract superclass. Concrete subclass will implement these methods. These method represent individual steps in an algorithm. In this way, superclass (abstract one) will control the flow (workflow) of algorithm. Subclasses just fill the gaps in superclass algorithm.

In this example this centralized workflow logic is example of inversion of control. In this approach the superclass is calling methods from subclass. This is fundamental approach for lean and clean code and code reuse.

Let's see example (this example can be put in one file for easy testing - it have only one public class):
/**
 * Abstract implementation -- class that control flow.
 * Describe algorithm for generic object creation.
 *
 */
abstract class CreateObject {
 
 protected Object[] datas = {"Kimmi", "Zuco", 1, 21};
 
 public void setData(Object[] data) {
  CreateObject.this.datas = data;
 }
 
 /**
  * Algorithm that control flow (IOC - Inversion of Control).
  * @return Object String representation. 
  */
 public String decorate() {
  StringBuilder sb = new StringBuilder();
  objectStart(sb);
  
  for (int i = 0; i < datas.length; i++) {
   Object data = datas[i];
   if (data instanceof String) {
    stringValue(sb, data, i);
   } else if (data instanceof Integer) {
    numberValue(sb, data, i);
   }
  }
  objectEnd(sb);  
  return sb.toString();
 }
 
 //these classes (down) need to be implemented in subclasses.
 abstract void objectStart(StringBuilder sb);
 
 abstract void objectEnd(StringBuilder sb);
 
 abstract void stringValue(StringBuilder sb, Object value, int indx);
 
 abstract void numberValue(StringBuilder sb, Object value, int indx);
 
}

/**
 * Object creation for JSON objects;
 *
 */
class JSONObject extends CreateObject {
 
 protected void objectStart(StringBuilder sb) {
  sb.append("\"Object\":").append("\n{");
 }
 
 protected void objectEnd(StringBuilder sb) {
  sb.append("\n}");
 }
 
 protected void stringValue(StringBuilder sb, Object value, int indx) {
  sb.append("prop")
    .append("\"").append(indx).append("\":")
    .append("\"").append(value).append("\",")
    .append("\n");
    
 }
 
 protected void numberValue(StringBuilder sb, Object value, int indx) {
  sb.append("prop")
    .append("\"").append(indx).append("\":")
    .append(value).append(",")
    .append("\n");
 }
}

/**
 * Object creation for xml objects.
 *
 */
class XmlObject extends CreateObject {
 
 protected void objectStart(StringBuilder sb) {
  sb.append("").append("\n");  }    protected void objectEnd(StringBuilder sb) {   sb.append("");
 }
 
 protected void stringValue(StringBuilder sb, Object value, int indx) {
  sb.append("")
    .append("prop")
    .append(indx)
    .append("")
    .append(value)
    .append("")
    .append("")
    .append("\n");  
 }
 
 protected void numberValue(StringBuilder sb, Object value, int indx) {
  sb.append("")
    .append("prop")
    .append(indx)
    .append("")
    .append(value)
    .append("")
    .append("")
    .append("\n");  
 }
 
}

public class DecorateData {
 
 public static void main(String[] args) {
  CreateObject xml = new JSONObject();
  System.out.println(xml.decorate());
 }
 
}
Lot of stuff going of there, but don't worry. Main thing to understand is flowing:

6 - 32: We declare abstract class that encapsulate workflow of creating string representation of object.
18 - 32: Implementation of algorithm - workflow. This algorithm use abstract methods (35 - 42) that need to be implemented by subclasses (He calls these methods from subclasses, hence Inversion of Control paradigm).
49 - 73: First implementation that implement abstract method and create JSON string object representation...nothing fancy.
79 - 111: Same thing, but for Xml Object representation.

112 - 120: Testing...

Conclusion

Such patterns as this offer good paradigm for separation of concerns. We can for example create superclass that will concentrate on business logic (and flow of that business logic), and use subclasses for primitive operation (technical stuff, JPA, servlets, parsing, JDBC,...).

It is useful to use Template method patter to capture an algorithm in one place, but deffer implementation of simple steps to subclasses. This has the potential to avoid bugs, by getting tricky operations right once in superclass and simplifying user code.

Please check post about Strategy design pattern that is very similar like Template, but instead abstract class uses interface.

Design Patterns in Java - Strategy

Introduction

Strategy pattern is alternative to Template method. But in case of Strategy pattern we use interface instead of abstract class. Please read more about this type of encapsulating logic in post about Template method if you are interested. Here we will here just show differences in correlation to TM.

You can download example of this Java code from my repository on google code:
https://code.google.com/p/codingwithpassionblog/source/browse/trunk/src/org/codingwithpassion/patterns/strategyMethod/DecorateData.java

Example

So in this case, class that knows the algorithm is not an abstract superclass, but a concrete class that uses a helper that implements an interface defining individual steps. You will use this type of pattern if you need to use concrete inheritance for some other purpose (because as we all knows Java and similar languages does not support multiple inheritance), or you just like this approach better because you are not forced to inherit from abstract class. Whatever is you reason, here is example:
/**
 * Concrete Object implementation. 
 * Here we implement workflow.
 */
class CreateObject {
 
 protected Object[] datas = {"Kimmi", "Zuco", 1, 21};
 
 public void setData(Object[] data) {
  CreateObject.this.datas = data;
 }
 
 /**
  * Algorithm that control flow (IOC - Inversion of Control).
  * @return Object String representation. 
  */
 public String decorate(DecoratorHelper helper) {
  StringBuilder sb = new StringBuilder();
  helper.objectStart(sb);
  
  for (int i = 0; i < datas.length; i++) {
   Object data = datas[i];
   if (data instanceof String) {
    helper.stringValue(sb, data, i);
   } else if (data instanceof Integer) {
    helper.numberValue(sb, data, i);
   }
  }
  helper.objectEnd(sb);  
  return sb.toString();
 }   
}
/**
 * Helper interface to which we defer individual steps.
 *
 */
interface DecoratorHelper {
 
 void objectStart(StringBuilder sb);
 
 void objectEnd(StringBuilder sb);
 
 void stringValue(StringBuilder sb, Object value, int indx);
 
 void numberValue(StringBuilder sb, Object value, int indx);
}

/**
 * Object creation for JSON objects;
 *
 */
class JSONObject implements DecoratorHelper {
 
 public void objectStart(StringBuilder sb) {
  sb.append("\"Object\":").append("\n{");
 }
 
 public void objectEnd(StringBuilder sb) {
  sb.append("\n}");
 }
 
 public void stringValue(StringBuilder sb, Object value, int indx) {
  sb.append("prop")
    .append("\"").append(indx).append("\":")
    .append("\"").append(value).append("\",")
    .append("\n");
    
 }
 
 public void numberValue(StringBuilder sb, Object value, int indx) {
  sb.append("prop")
    .append("\"").append(indx).append("\":")
    .append(value).append(",")
    .append("\n");
 }
}

/**
 * Object creation for xml objects.
 *
 */
class XmlObject implements DecoratorHelper {
 
 public void objectStart(StringBuilder sb) {
  sb.append("").append("\n");
 }
 
 public void objectEnd(StringBuilder sb) {
  sb.append("");
 }
 
 public void stringValue(StringBuilder sb, Object value, int indx) {
  sb.append("")
    .append("prop")
    .append(indx)
    .append("")
    .append(value)
    .append("")
    .append("")
    .append("\n");  
 }
 
 public void numberValue(StringBuilder sb, Object value, int indx) {
  sb.append("")
    .append("prop")
    .append(indx)
    .append("")
    .append(value)
    .append("")
    .append("")
    .append("\n");  
 }
 
}
/**
 * Testing...
 *
 */
public class DecorateData {
 
 public static void main(String[] args) {
  CreateObject xml = new CreateObject();
  
  System.out.println(xml.decorate(new XmlObject()));
 }
 
}
37 - 46: First we move template methods into an interface. Definition is same as in previous example.
52 - 76, 82 - 114: In implementation of our interface we do not need to subclass anything anymore. But note that we must change access mode of method to public because this time we will to access them from outside class hierarchy.
17: Note that we need to provide interface type to our template method. This type will be substitute to concrete instance of class at runtime (Polymorphism is great stuff!). Method is exactly same as in TM example.

Which to choose?

This approach is more complex, but is more flexible. This is classic example of trade-off between concrete inheritance and delegating to an interface. Decision what to choose is completely up to you and may be influenced by circumstances like: Class implementing steps needs its own inheritance hierarchy, how many steps are involved, how many different implementation will you have...

Wednesday, September 29, 2010

jQuery triggering custom event (Observer pattern)


Introduction

We all know what basic events in JavaScript and jQuery are. They represent handlers that are triggered at specify event (click, timer, mouse move, etc.). But how do we create custom events that are triggered on our command, here comes jQuery to the rescue! Also doing this (calling custom events), we can simulate classic Go4 observer pattern (publish/subscribe).

Using jQuery is beneficiary, because, we are not concerned about various DOM levels, browser specific stuff (like: (event.target) ? event.target : event.srcElement;...), does IE 6,7,8 support event capture phase, and stuff like that. We basically create another abstraction level over various JavaScript implementations.

So, let the fun begin!

Live event handling

In our example we will use jQuery ability to manage event handler on the fly (as we manipulate the DOM by adding or removing elements). This means that we will proactively establish event handlers for elements that don't exist yet. jQuery provide this functionality with the live() method. Syntax for this method is similar like bind() or for example click() method.

Triggering events

In out example we will also need some method that will automatically invoke (trigger) event handlers on our behalf under script control. For this we will use the trigger method. This method does its best to simulate the event to be triggered. One curiosity is that it even populate instance of jQuery event (event object in jQuery style :) ), but because there is no real event, properties that report event-specific values such as the location of mouse x and y cordinates, have no value. Ok, let's move on.

Example

First jQuery part:

$(function() { //Wait until DOM is fully loaded .
    $('#addBox').click(function() {
        $('td.box:first-child').clone().appendTo('tr.boxLine');                
    });

    $('#paintBlue').click(function() {                
        $('td.box').trigger('paintThem');
    });

    $('td.box').live('paintThem', function() {
        $(this).css('background', 'blue');                
    });            
});

2-5: First we create simple click handler that add new box like element on the DOM. We create boxes using simple table and just adding new table data elements by coping them. Please see html part, and first picture where we add couple of boxes.

6-8: Here we trigger custom event named "paintThem". This is simple click event triggered by button. We need to trigger custom event on elements (in this case 'td.box') that posses custom event (but, also we can trigger standard events like: click, hover...).

10-12: The "real meat" of this whole story. Here we see a use of the live() method to proactively establish event handlers. The 'td.box' elements will be added dynamically to the DOM and live method will automatically establish handlers as necessary.
This way, we sat it up _once_ and jQuery will handle the details whenever an item that matches that selector (td.box) is create (or destroyed). Great stuff!

So as you can see, this example is not so fancy, it just paint red boxes to blue. But the way it does it is interesting. I can also walk trough all elements and paint them to certain color, but this approach is much cleaner and in some situations better (asynchronous refresh (AJAX) for example).

Then, html part. My apologies for this fuzzy looking html code (it's blogger fault! :) ).


Custom event is a very useful concept. Using it, we can attach code to an element as a handler for a custom event, and cause it to execute by triggering the event. The beauty of this approach, as opposed to directly calling code, is that we can register the custom handlers in advance, and by simply triggering the event, cause any registered handlers to be executed, without having to know they've been established.

Custom event concept in jQuery can be seen as limited version of Observer pattern. In this pattern (also know as publish/subscribe pattern) we subscribe an element to a particular event by establishing a handler for that element, and then when the event is published (triggered), any elements that are subscribe to that event will automatically invoke their handlers.

In this way we are creating loose coupling (and that is always a _good_ idea) in our JavaScript code. This make our code cleaner and meaner!

Custom trigger in action:

Adding boxes.


Triggering event to paint boxes in blue.