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.