2013 in review

Posted: December 31, 2013 in Tutorials

The WordPress.com stats helper monkeys prepared a 2013 annual report for this blog.

Here’s an excerpt:

The concert hall at the Sydney Opera House holds 2,700 people. This blog was viewed about 21,000 times in 2013. If it were a concert at Sydney Opera House, it would take about 8 sold-out performances for that many people to see it.

Click here to see the complete report.




Introduction

Few days back I was trying to port my Android Game Development Kit (GDK) into HTML5 (JavaScript based GDK), for that I got a chance to explore Classes (object oriented) in JavaScriptPlease note that I am not an expert of JavaScript, and in this tutorial I have tried to cover all the searches and efforts that I put to get my JavaScript code running in Object Oriented (Classes).

To Keep this tutorial simple I will use very simple example instead of complex game related domain ideas. and will not discuss what OOP is and how and where classes are used in greater or expert level details. I will assume that readers have the knowledge of object oriented programming (using classes in code).

In real life we see different animals. All the animals have few characteristics, habits and actions, and whenever we have to handle such an information for more than one (repeatedly) we think in terms of a Class in computer software programming. Similarly there is another thing which drive us to use class and that is grouping the similar actions and characteristics in one place, again OOP Class is our best shot.

We know that most of the animals have names(Puppy, ScubyDuby), type(Cat, Dog, Lion, Elephant, Tiger etc), color, age etc. so we will group all these information into one Class (Class is basic template or blueprint for some thing)

Animal{
    name
    type
    color
    age
}

Now for each different animal we will create an object (Instantiation of object of the blueprint/template (i.e. Class)). An object of type Animal(Class). and then we will populate the attributes with the required information.
examples are as follows.

Animal
{
    name: "Tango"
    type: "Lion"
    color: "Yellow"
    age: "2 years"
}
Animal
{
    name: "Suzi"
    type: "Elephant"
    color: "Black"
    age: "4 years"
}

We can see that we have grouped and encapsulated relevant information of a particular real life object(the one we see in real world). and now we can store and manipulate this information easily.

before jumping to actual class, lets compare ordinary way and using classes.

	//populating variables
    var animal_1_name = "Tango";
    var animal_1_type = "Lion";
    var animal_1_color = "Yellow";
    var animal_1_age = "2 years";

    var animal_2_name = "Suzi";
    var animal_2_type = "Elephant";
    var animal_2_color = "Black";
    var animal_2_age = "5 years";

    //printing this information
    var str = "** Here is detail of first animal **\n";
    str += "Name: "+ animal_1_name +"\n";
    str += "Type: "+ animal_1_type +"\n";
    str += "Color: "+ animal_1_color +"\n";
    str += "Age: "+ animal_1_age +"\n";

    str += "** Here is detail of Second animal **\n";
    str += "Name: "+ animal_2_name +"\n";
    str += "Type: "+ animal_2_type +"\n";
    str += "Color: "+ animal_2_color +"\n";
    str += "Age: "+ animal_2_age +"\n";

    alert(str);

We can see that there is no such boundary or nothing the code is pretty much messed up and more lines of code. which makes it less manageable ( Consider an example in which we require the information of 10 different animals)

Similarly OOP based code

   var animal_1 = new Animal("Tango", "Lion", "Yellow", "2 Years");
   var animal_2 = new Animal("Suzi", "Elephant", "Black", "5 Years");
   alert(animal_1.getDetail());
   alert(animal_2.getDetail());

We can see our code is very nice and clean and we only concentrate on our logic in main script instead of handling different variables or related information. Similarly we are reusing functionality. likegetDetail() will format string as we want. moreover if in the future we want to change some formatting or want to add an extra field, we don’t have to change code for 10 different animals and resolving the code changes. We will only make a change in relevant class that will be shared(depicted) everywhere, our main script code will be almost intact.

That’s it, I will not go in further object oriented details

Now lets get straight to JavaScript class.

2. JavaScript Class

Every function in JavaScript can behave as a class, and that’s how we define classes in JavaScript.

//class declaration + constructor of class
function Animal( name , age ){
	this.name = name; 
  	this.age = age;
}

//class attributes definitions
Animal.prototype.name = "Animal";
Animal.prototype.age = 0;

//class functions declaration and body
Animal.prototype.getDetail = function(){
	return "Name: " + this.name + "\n"
		  +"Age: "+this.age + "\n";
}

In example above we have defined a class(Animal) that have only 2 attributes (name and age) and only one method/function (getDetail())

2.1 Implementation

var a = new Animal("Kitty", 2);
//alert complete detail
alert(a.getDetail());

//access an attribute of a class (you can also write getter and setter function)
a.name = "Mimi";

//alert complete detail
alert(a.getDetail());

2.2 Access Modifier in JavaScript

2.2.1 Public

In our Animal class we have created 2 variables name and age. both are public variable as we have defined them with following line of code.

Animal.prototype.name = "Animal";
Animal.prototype.age = 0;

//these are accessible with this with in the class methods
this.name

//and can be accessed out of the class by using its instantiated object
objAnimal.name

In simple terms where ever we use this operator with a variable it mean its a public variable.

this.name = name; 
this.age = age;

  return "Name: " + this.name + "\n"
		  +"Age: "+this.age + "\n";

2.2.2 Private

In order to have private variables we have to trick JavaScript in following way.

function Human() {

    //public
    this.name = "Mazhar Hassan";

    //private
    var _age = 5;

    //Getter/Setter to access private variables
    //Please note these getter setter themselves will be public
    this.getAge = function(){
        return _age;
    };
    this.setAge = function(age){
        _age = age;
    };
}
Human.prototype.name = "";
Human.prototype.getName = function() {
	return this.name;
}

//Now we can access this private variable
var h = new Human();
alert(h.getAge());
h.setAge(23);
alert(h.getAge());

2.3 Static variable in JavaScript

Again there is no reserve word for creating static variables, its the way how we access that variable. These are private variables we defined in previous example, only difference is getter and setter methods.

function Human() {

    //public
    this.name = "Mazhar Hassan";

    //private
    var _age = 5;

    //Getter/Setter to access private variables
    //Please note these getter setter themselves will be public
    this.getAge = function(){
        return _age;
    };
    this.setAge = function(age){
        _age = age;
    };

    //private static variable
    var _password = "";

    //public getter/setter for static variable
    Human.prototype.setPassword = function( password ) {
    	_password = password;
    }
    Human.prototype.getPassword = function() {
    	return _password;
    }

}
Human.prototype.name = "";
Human.prototype.getName = function() {
	return this.name;
}

//IMPLEMENTATION --------------------------------------------------
var h1 = new Human();
var h2 = new Human();

h1.setPassword("xyz");
h2.setPassword("abc");

alert(h1.getPassword()+" = "+h2.getPassword()); //will print "abc = abc"

3. Inheritance in JavaScript

Concept of inheritance in JavaScript is same like few other languages. As we already know in order to create a class in JavaScript we have to define a function that can behave as a class. lets define a Dogclass, that will inherit Animal class.

//Dog class inherits Animal Class
Dog.prototype = new Animal();

//Dog Class + constructor
function Dog( name , age){
	this.name = name;
	this.age = age
}

//speak function of Dog
Dog.prototype.Speak = function(){
	alert("waoo waoo");
}

3.1 Implementation

The implementation is pretty much same we are still able to access function and attributes of parent class(Animal) using child class(Dog).

var d = new Dog("Skubby", 2);
alert(d.getDetail());

The Dog class we previously created is inheriting Animal class and have introduced a new function called speak hence we can add more functions and attributes when ever we need to extend any functionality.

3.2 Calling Parent Constructor

In the constructor of child class we can make a call to parent constructor. our previous constructor of child class looks like as follows.

function Dog( name , age){
	this.name = name;
	this.age = age
}

We simply replace it by calling parent constructor.

function Dog( name , age){
	Animal.call(this,  name, age);
}

and following code will return the same result as were before.

var d = new Dog("Skubby", 2);
alert(d.getDetail());

3.3 Overriding a method/function of parent class (Method Overriding)

Now we will override method of a parent class in child class.

//Dog class inherits Animal Class
Dog.prototype = new Animal();

//Dog Class + constructor
function Dog( name , age){
	Animal.call(this, name, age);
}

//speak function of Dog
Dog.prototype.Speek = function(){
	alert("waoo waoo");
}
//Overriding method
Dog.prototype.getDetail = function() {
	return "--- This is a DOG object ---\n";
}

3.4 Calling function of parent class

Syntax

<parent-class-name>.prototype.<method-name>.call(this <,method-arguments>);
Example: Animal.prototype.getDetail.call( this ); 

//Dog class inherits Animal Class
Dog.prototype = new Animal();

//Dog Class + constructor
function Dog( name , age){
	Animal.call(this, name, age);
}

//speak function of Dog
Dog.prototype.Speek = function(){
	alert("waoo waoo");
}
//Overriding method
Dog.prototype.getDetail = function() {
	return "--- This a DOG object ---\n"
		  + Animal.prototype.getDetail.call( this );
}

3.5 Multiple Inherence in JavaScript

Simple answer to multiple inheritance is, JavaScript does not support multiple inheritance just like Java programming language. We know that in order to inherit a class we use following code

Dog.prototype = new Animal();

If you think by Inheriting another class in similar way will work, then you are wrong it will actually replace the inheritance

//Dog is inheriting Animal class
Dog.prototype = new Animal();

//Dog is NOW inheriting Bird class
Dog.prototype = new Bird(); //Previous declaration is overwritten

However there are few workarounds to get the feel of multiple inheritance but that is not actually real inheritance. you can using cloning technique to clone the functions of any other parent class to your child class. however that is not in the scope of this tutorial.
Here are few links that have provided few ways to achive mulitiple inheritence in different ways.
1 -Multiple Inheritance in Javascript
2 -Experimenting With Multiple Class Inheritance In Javascript
3 -Implementing Multiple Inheritance in Javascript
4 -Multiple inheritance in javascript : StackOverflow : Read the last comment by MooGoo, The simplest way to understanding the trick of multiple inheritence.
5 -Classical Inheritance in JavaScript : I have strong recommendation to read this link, it explain different types/styles of Inheritance as well defining class in JavaScript




About Muhammad Mazhar Hassan

Author: M Mazhar Hassan

Dependency Injection (DI)

As the name imply injecting a required dependency. This should be at runtime instead of compile time, which makes it a real dependency injector.

Spring Framework Tutorial – Bean Creation – Part1
Spring Framework Tutorial – Inversion of Control – Part2

This can be useful if we need to load modules dynamically based on some decision or loading of any control, or any plug-in. I have used this technique in many games, where an Enemy manger handles all the enemies on the stage; they might belong to different categories, like human, robot or animal enemy. So a decision on runtime is made what type enemy need to add onto the stage. A common controller injects that enemy object as per requirement and situation of the game level. Here in this tutorial we will not go to that detail of complexity, rather stay on simple examples to better understand the Dependency Injection (DI) in Spring framework using java programming language in reference to Inversion of Control (IOC).

Inversion of Control (IOC)

“Do not instantiate me I will be instantiated myself (by external factor)”

As discussed in previous tutorial, IOC uses container based dependency injection, as and when required. According to few people Inversion of Control – IOC and Dependency Injection- DI is one and same thing, according to my understanding they are different in following way.

Dependency can be injected by any entity. For example we can request an XYZ pattern/code to provide an object of specific concrete class based on any runtime decision. But in case of IOC, instead of requesting for a particular dependency, Spring Container himself injects a required dependency whenever it is required by code (Control is inverted / reversed / dependency of an object is inverted), and maintains its life cycle. Please note that IOC is a big picture whose one part is Dependency Injection, which works similar to phrase “Don’t call us, we will call you”. And in our tutorials we will use IOC for our dependency injection.

Note: Several dependencies which are going to be injected to needy classes/modules must have common/compatible abstraction in order to be used interchangeably. In our example Lion and Elephant both are sharing same Animal interface. Injection of Lion or Elephant does not matter for AnimalService Class, because it’s not dependent on concrete classes, if in future we add a new concrete class let say a Dog class extending from Animal interface, it will work transparently and change in code/and recompilation for AnimalService class will not be required.
For more explanation please read Part II of this tutorial series. Spring Framework Tutorial – Inversion of Control – Part2

Benefits of IOC

  1. Lose coupling: As objects do not create other objects, Instead Container create those required object and inject them as per requirement.
  2. Plug & Play: A simple configuration makes a module or class available to you where ever you require (runtime availability).
  3. Layered System: due to support of modules and lose coupling it divides your code into layers. In our Zoo example Animal Service expose few methods that can be performed by any class or another service. Concrete classes have the internal implementation how a task can be performed. (Have a look on Part 2 for Zoo example)Let say we want to know what is the name of the sound of an animal so AnimalService(Layer 1) class is used to objAnimalService.soundName() if its Lion it will print Roar and if its Elephant it will print Trumpeting. Lion and Elephant are 2 concrete classes (Layer 2) used by AnimalService class. And we know that AnimalService classes does not take the burden to create the objects of 2 concrete classes as well it does not care about what concrete classes are available, and which one is required, Here the Spring IOC (Layer 3) take all the responsibility of creating the require objects and inject them in service class as well it takes the responsibility to manage their life cycle. Here this third layer is also responsible for mapping required dependency (Lion or Elephant) through a configuration in xml file or Annotation.
    “It enables developer to program reusable code and problem-specific code independently”
  4. Sharing: Resource can be shared easily.
  5. Testing: As we reduce dependency among the modules and classes, so unit testing for each piece of code is very easy.
  6. Integration: IOC or Spring help us integrating different modules.
  7. Easy replacement: As modules does not care about what other modules or subsystem will do (because they rely on contracts [e.g. Interface]), hence replacing them does not effect requiring modules or any other modules.

Components of Dependency Injection

  1. Dependent: The one who requires a dependency to complete his task. In our zoo example its AnimalService class. This defines what type of class object it will require by using an Animal interface.
  2. Dependency: It is the one acquired by others, and they contain there specific implementation of abstraction. In our example its Elephant and Lion classes that are extended by a common interface (i.e. Animal).
  3. Injector: This is the one responsible for creating an instance of dependency and injects it to the dependent class/module. In our example it’s IOC-Spring Container. Injector is aware of the concrete classes (thought an xml file or an annotation – Lion & Elephant) that fulfill the requirements of dependent ( as dependent have specified an interface that is required by him). In our example Elephant & Lion are 2 concrete classes that are extended from Animal interface.

Implementation Techniques

There are many techniques as described by Wikipedia.org, like factory pattern, service locator pattern and contextual lookup but for Spring IOC we will concentrate on following techniques and especially on first 2.

  1. Setter Injection
  2. Constructor Injection
  3. Interface Injection

Configuration Techniques

  1. XML file.
  2. Annotation.

If we remember our previous tutorial, we have used xml file for our mapping/configuration of beans. And we have used a setter method for injection. Have a look at figure above.

1 – XML Configuration

I personally prefer XML based configuration because I only change in xml file to integrate/inject different modules without recompiling classes. But it all depends what kind of requirements you have. But for this tutorial series I will use xml based configuration.

A – Setter Injection

We have used this method in previous tutorial, for the purpose of completeness I will copy paste code and xml configuration from previous tutorial. Let’s have a look on previous example diagram

Animal.java

package com.mazhar.zoo;
public interface Animal {
	public String speak();
}

Lion.java

package com.mazhar.zoo;
public class Lion implements Animal {
	@Override
	public String speak() {
		return "Roar";
	}
}

Elephant.java

package com.mazhar.zoo;
public class Elephant implements Animal {
	@Override
	public String speak() {
		return "Trumpeting";
	}
}

AnimalService.java

package com.mazhar.zoo;
public class AnimalService {
	private Animal animal;

	public Animal getAnimal() {
		return animal;
	}
	public void setAnimal(Animal animal) {
		this.animal = animal;
	}
	public void printSoundName(){
		System.out.println(animal.speak());
	}
}

Context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans 
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="Elephant" class="com.mazhar.zoo.Elephant"></bean>
	<bean id="Lion" class="com.mazhar.zoo.Lion"></bean>

	<bean id="LionService" class="com.mazhar.zoo.AnimalService">
		<property name="animal">
			<ref local="Lion"/>
		</property>	</bean>
	<bean id="ElephantService" class="com.mazhar.zoo.AnimalService">
		<property name="animal">
			<ref local="Elephant"/>
		</property>	</bean>
</beans>

I we look carefully at xml configuration

<bean id="ElephantService" class="com.mazhar.zoo.AnimalService">
	<property name="animal">
		<ref local="Elephant"/>
	</property>
</bean>

We have defined a bean with id ElephantService which is pointing to com.mazhar.zoo.AnimalService. And we have injected a concrete class (Elephant) through setter method.

<property name="animal">
		<ref local="Elephant"/>
</property>

SprintTestApp.java

package com.mazhar.zoo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SprintTestApp {

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

		AnimalService serviceLion = (AnimalService) context.getBean("LionService");
		serviceLion.printSoundName();

		AnimalService serviceElephant = (AnimalService) context.getBean("ElephantService");
		serviceElephant.printSoundName();
	}
}

Dependencies

In order to run above lines of code for spring we will require following jar files from the Spring framework as well few common libraries for logging etc.

[Spring related]
org.springframework.asm-3.0.0.M3
org.springframework.beans-3.0.0.M3
org.springframework.context-3.0.0.M3
org.springframework.context.support-3.0.0.M3
org.springframework.core-3.0.0.M3
org.springframework.expression-3.0.0.M3

[Common]
antlr-runtime-3.0
commons-logging-1.0.4

B – Constructor Injection

This is also very simple code, in order to extend our example we will add another class to our project with a constructor that take an animal interface argument as a parameter.

package com.mazhar.zoo;
public class AnimalConstructorService {
	private Animal animal;
	public AnimalConstructorService(Animal animal){
		this.animal = animal;
	}
	public void printSoundName(){
		System.out.println(animal.speak());
	}
}

XML Configuration

<bean id="DogService" class="com.mazhar.zoo.AnimalConstructorService">
	<constructor-arg ref="Dog" />
</bean>

That’s it, we can now call this service bean as follows

AnimalConstructorService service2 = (AnimalConstructorService)context.getBean("DogService");
service2.printSoundName();

Please note that you can inject anything to a constructor/setter method, which can be an a value (String/ integer etc) or a reference.

Multiple arguments

Multiple arguments can be passed to a constructor in following way

<bean id="HumanService" class="com.mazhar.human.Developer">
	<constructor-arg index="0" value="007" />
	<constructor-arg index="1" value="Muhammad Mazhar Hassan" />
</bean>

Next Tutorial:

This tutorial is already prolonged too much, in next tutorial we will discuss about Interface injection and Configuration through annotation and different collection support in Spring using xml based configuration. (if you are too eager to learn everything about Spring Framework now Please have a look on 3rd link in references section.

Source Code

Source Code : Spring-ioc-XML.zaip
Please download the source code in order to see things in action, I have not included jar files in project, I don’t know why but I just haven’t. But you can download spring frame work from Spring source

http://www.springsource.org/download

http://www.springsource.org/download/community

I have downloaded spring-framework-3.1.1.RELEASE.zip from http://s3.amazonaws.com/dist.springframework.org/release/SPR/spring-framework-3.1.1.RELEASE.zip

Refrences

IOC

http://en.wikipedia.org/wiki/Dependency_injection

http://www.vogella.com/articles/SpringDependencyInjection/article.html

Nice tutorial on Spring Framework, instead of beating around the bushes hit hard at the heart, easy copy paste implementable examples.

http://www.roseindia.net/tutorial/spring/spring3/ioc/index.html

idref in Spring: The idref element allow you to pass the bean id (which is the string value not the reference) of another bean in the container

http://www.roseindia.net/tutorial/spring/spring3/ioc/springidrefelement.html

Spring inner bean:

http://www.roseindia.net/tutorial/spring/spring3/ioc/springinnerbean.html

Service locator:

http://grantpalin.com/2009/06/11/reducing-code-coupling-service-locator/

Dependency Injection:

http://grantpalin.com/2009/10/14/reducing-code-coupling-dependency-injection/

Contextual Lookup: http://www.java2s.com/Tutorial/Java/0417__Spring/ContextualizedDependencyLookupDemo.htm

http://www.java-forums.org/blogs/spring-framework/406-contextualized-dependency-lookup-spring.html

http://stackoverflow.com/questions/6550700/inversion-of-control-vs-dependency-injection



Inversion of Control – IOC is a technique which helps in object creation at run time instead of compile time. And whenever or wherever a particular object or a collection of objects are required, this sort of binding is achieved with the help of dependency injection.

Please read Part1 of this tutorial if you are new to Spring Framework.

Inversion: The state of being inverted, reversal of the usual, or reverse in position, order, direction, or relationship.

“Do not instantiate me I will be instantiated myself (by external factor)”
In our case, we do not instantiate objects rather they are instantiated automatically whenever required by our program. This auto instantiation is handled by Spring framework using dependency injection.

Tight Coupling
IOC deals with problem of Tight Coupling. (This concept of explanation is taken from a tutorial by Shivprasad koirala, excellently explained by him, I couldn’t resist myself taking the basic idea of explanation from him – Please have a look on this link)

Let’s bring our zoo example in here to be consistent with our series of tutorials.

package com.mazhar.zoo;
public class AnimalService {
	private Elephant obj;

	public AnimalService(){
		obj = new Elephant();
	}
}

The above example leads to 3 main issues.

1 – Life cycle dependency: AnimalService class is responsible for instantiation of Elephant object, so the service class is responsible for life cycle of the Elephant class. And if for some reason instantiation of Elephant class fails will also fail the instantiation of AnimalService class. Because Elephant class’s object is being created in the constructor of service class.

2 – Tight coupling: As we can see Elephant class is directly referenced in the AnimalService class which makes them tightly coupled. So any change in Animal (Elephant) class might lead to recompilation of service class.

3 – Concrete class dependency: Our service class is dependent on concrete class of animal (i.e. Elephant). And if we add a new Animal class (Lion) this will also require changes in our service class. And hence lead to recompilation of service class.

Getting out of problem: Now how can we handle this problem, surely the solution is IOC in our case (as we are exploring Spring Framework) but what is key factor which help us to achieve the solution for this problem?
The Answer to the question is, first remove the process of object instantiation from service class, secondly instead of using concrete class use abstraction and inject the required concrete class as per requirement.

Here IOC of Spring frame work will help us to achieve this result by shifting the object creation task/role/control from the Service class to Spring. Now we can say that we have inverted the objection creation and injection control from service class with the help of Spring.

Animal.java

package com.mazhar.zoo;
public interface Animal {
	public String speak();
}

Lion.java

package com.mazhar.zoo;
public class Lion implements Animal {
	@Override
	public String speak() {
		return "Roar";
	}
}

Elephant.java

package com.mazhar.zoo;
public class Elephant implements Animal {
	@Override
	public String speak() {
		return "Trumpeting";
	}
}

AnimalService.java

package com.mazhar.zoo;
public class AnimalService {
	private Animal animal;

	public Animal getAnimal() {
		return animal;
	}
	public void setAnimal(Animal animal) {
		this.animal = animal;
	}
	public void printSoundName(){
		System.out.println(animal.speak());
	}
}

Context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans 
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="Elephant" class="com.mazhar.zoo.Elephant"></bean>
	<bean id="Lion" class="com.mazhar.zoo.Lion"></bean>

	<bean id="LionService" class="com.mazhar.zoo.AnimalService">
		<property name="animal">
			<ref local="Lion"/>
		</property>	</bean>
	<bean id="ElephantService" class="com.mazhar.zoo.AnimalService">
		<property name="animal">
			<ref local="Elephant"/>
		</property>	</bean>
</beans>

SprintTestApp.java

package com.mazhar.zoo;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SprintTestApp {

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

		AnimalService serviceLion = (AnimalService) context.getBean("LionService");
		serviceLion.printSoundName();

		AnimalService serviceElephant = (AnimalService) context.getBean("ElephantService");
		serviceElephant.printSoundName();
	}
}

Previous – Spring Framework Tutorial – Bean Creation – Part1
Next – Spring Framework Tutorial – Dependency Injection – Part3

References

For more detail please have a look on following links.

Inversion of Control – Wikipedia

Design pattern – Inversion of control and Dependency injection




Today we will explore a very basic of Spring framework using Java. We will start from basic example to complex. In this tutorial I will not overload you with thousand of definitions and terminology right from the start. We will cover them as we progress.

Zoo Example

In this example we will use the simplest form of spring that can be used with java. We will create a simple class, and will request spring to get the object of that class. There are many benefits using Spring in the mid of object creation, as Spring has its own container so all the life cycle of the object is handled internally by Spring Container.

Lion.java

package com.mazhar.zoo;

public class Lion {
	public String speak() {
		System.out.println("roar");
	}
}

Above is a simple class not much to do, contain only one method. We can call this function directly by creating an instance of this class and make call to speak() function using the instantiated object.

Lion obj = new Lion();
obj.speak();

Now let’s get this object from Spring.

ZooTestApp.java

package com.mazhar.zoo;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ZooTestApp {

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
		Lion obj = (Lion) context.getBean("LionBean");
		obj.speak();
	}

}

In above code we have instructed the Application Context to read an xml file which contains all the mapping of the Beans/Classes/etc.
Now we can get any bean from the context, In this case we have requested for LionBean.

Context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans 
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="LionBean" class="com.mazhar.zoo.Lion" />
</beans>

In the xml mapping above lets concentrate on this line.

<bean id="LionBean" class="com.mazhar.zoo.Lion" />

I have defined a bean with id LionBean which is mapped onto my Lion class, please note that I have provided the complete package path com.mazhar.zoo.Lion, its always better to get rid of any inconsistency.
Hurray! You are done with your first Spring example.

Dependencies

In order to run above lines of code for spring we will require following jar files from the Spring framework as well few common libraries for logging etc.

[Spring related]
org.springframework.asm-3.0.0.M3
org.springframework.beans-3.0.0.M3
org.springframework.context-3.0.0.M3
org.springframework.context.support-3.0.0.M3
org.springframework.core-3.0.0.M3
org.springframework.expression-3.0.0.M3

[Common]
antlr-runtime-3.0
commons-logging-1.0.4

Conclusion

Now first question comes into mind why we are using Spring framework?
In this part our example was so simple so we might not be able to see much of benefit. But still we know that the life cycle of the object is controlled by Spring, like when to create and when to destroy. This greatly improves your performance when you are working on huge applications. And lots of object creation is involved. It can behave in a way that whenever you request a specific bean every time same instance of the object is returned to you(Singleton). It also behaves like a Factory pattern, like as we proceed we will create more Animal Classes in our zoo package and Spring will help us in returning specific type of object.
Beside this Spring can help you in MVC, JDBC, IOC, AOP, modularity and much more which we will be covered step by step in upcoming tutorials.

Spring Framework Tutorial – Bean Creation – Part1
Spring Framework Tutorial – Inversion of Control – Part2
Spring Framework Tutorial – Dependency Injection – Part3

References

For more detail please have a look on following links.
Introduction to the Spring Framework by Rod Johnson

Spring Bean Example, Spring Bean Creation





Today we will learn how to compile source code and genrate a war file for our web project.

[Desired WAR Structure]

First of all I will explain the structure of WAR file which is deployable on jboss. (here i will take an exmaple of spring MVC web project).

for that we need to understand the structure of war file. in following listing I have mentioned important part of the war file.

SpringWebExample.war
  |   index.jsp
  |    
  + - META-INF
  + - WEB_INF
  	|   disp-servlet.xml
  	|   web.xml
  	+ - classes
  	|	(all class files)
  	+ - jsp
  	|	(jsp i have used for mvc)
  	+ - lib
  		(all required jar files - spring releated etc)

Structure of Project

Here is how my project is structured in eclipse, Please note that i will not mention eclipse related files (configuration etc.)

SpringWebExample
  |   
  + - src
  |      +com.mazhar.spring
  |           -MazController.java
  |
  + - WebContents
		| - index.jsp
		|
		+ - META-INF
		|            
		+ - WEB_INF
			| -  disp-servlet.xml
			| -  web.xml
			|                
			+ - jsp
				- welcome_maszhar.jsp
				- goodbye_maszhar.jsp

Strategy

Now we understand what is the structure of our project and what will be strtucture of our resulatant war file.
We know that our java files need to be compiled into class files and required(dependent) jar files need to be included into the war file,so that application run smoothly on Jboss Server. Hence following would be our steps for genrating a jar file.

1 - First step is to crate a build.xml file in same project space, which will have all the required instructions to run an ANT Script.

2 - We will also crate another file "build.properties" in same folder, this will hold our common settings and paths to different location.
	* It will have a property that point to jboss lib folder.
	* It will have a property that point to jboss deploy folder.
	* etc.
6 - We will create another folder locallib in same project.
	* It will keep all spring fromework relevant jar files or any other jar file which is requred to complie this project and also will be required to run this application on jboss (becuase we will packge these jars into our WAR file as well).

3 - In build.xml file we will define our project and few variables that point to src, webContent, build folder etc.

4 - Next we will define our class path.
	* In this section we will mention different locatiions for external jars that are required to compile our project.
	* like my custom lib folder which holds all the spring framework related jar files.
	* like a servlet-api.jar file(s) that are placed in jboss lib folder.
	* etc
5 - We will define some targets which will be called from command line.
	* example
		ant clean
		ant build

6 - ANT script will perform following steps
	6.1 It will create "build" folder within the same project space, where all of the complied classes will be genrated.
	6.2 Now it will compile java files from src folder and keep their genrated class files in build/classes/ folder.
	6.3 Now ANT script will create a war file by including contents of the webContent folder.
		* ANT script will also include all jar files from locallib into SpringWebExample.war/WEB-INF/lib folder.
		* ANT script will also include all class files from build/classes into SpringWebExample.war/WEB-INF/classes folder.

7 - We can find our SpringWebExample.war in build folder.

Here is how out war file look like

SpringWebExample.war
- index.jsp
+ META-INF
+ WEB-INF
disp-servlet.xml
web.xml
+ Classes
+ com.mazhar.spring
- MazController.class
+ Jsp
- welcome_mazhar.jsp
- goodbye_mazhar.jsp
+ lib
- org.springframework.asm-3.0.5.RELEASE.jarorg.springframework.beans-3.0.5.RELEASE.jar

org.springframework.context.support-3.0.5.RELEASE.jar

org.springframework.context-3.0.5.RELEASE.jar

org.springframework.core-3.0.5.RELEASE.jar

org.springframework.expression-3.0.5.RELEASE.jar

org.springframework.web.servlet-3.0.5.RELEASE.jar

build.properties

	server.lib=D:/jboss/server/default/lib

build.xml

<?xml version="1.0" encoding="UTF-8"?>
<project name="SpringWebExample" basedir="." default="usage">
    <property file="build.properties"/>
    <property name="src.dir" value="src" />
    <property name="web.dir" value="WebContent" />
    <property name="build.dir" value="${basedir}/build" />
    <property name="name" value="SpringWebExample" />

    <path id="project-classpath">

    	<!--  here give path for jar repository -->
    	<fileset dir="${server.lib}">
    		<include name="servlet*.jar" />
    	</fileset>
    	<fileset dir="${basedir}/locallib">
    		<include name="*.jar" />
    	</fileset>
    	<pathelement path="${build.dir}" />
    </path>

    <target name="build" depends="compile" description="build project, but first compile it">
         <war destfile="build/${name}.war"
             webxml="${web.dir}/WEB-INF/web.xml">
             <lib dir="${basedir}/locallib"/>
             <classes dir="${build.dir}/classes" />
            <fileset dir="${web.dir}">
                <include name="**/*.*"/>
            </fileset>
        </war>
    </target>

    <target name="compile" description="Compile java files and place them webContents/web-inf/">
    	<mkdir dir="${build.dir}/classes"/>
        <javac destdir="${build.dir}/classes" failonerror="true">
            <src path="${src.dir}"/>
            <classpath refid="project-classpath"/>
        </javac>
    </target>

    <target name="clean">
    	 <delete dir="${build.dir}" failonerror="true"/>
    </target>
</project>

Execute

cmd>ant clean build

or

cmd>ant clean
cmd>ant build

XML DATA SOURCE ( using List Instead of sub-report)

Hi folks today we will learn how to generate PDF reports with Jasper reporting engine. using iReport (a front end tool for design and testing your reports)  and XML as data source (using XPATH).
and finally we will display information in such a way that shows how to get sub-report functionality without actually using sub-report.

How the system works, Jasper Engine require a report in JRXML, its a basic XML format used for reporting which jasper engine can understand.

JRXML file contains styles variable fields etc. pretty much every thing that is require to render a report.

(I am not going to cover much detail about JRXML right now. and we will proceed to our tutorial. based on asumption you know how to use iReport and JRXMLs)

XML Datasource

XML is very popular way for exchanging/sharing information across the applications and platforms. It also very neat and clean way to describe your data. Recently I was working on an application where data was required to be shared through web service, the same data needed to be exported  for other applications and finally the same data was required to be printed as PDF report, so XML was the only solution in my case. Plus I can change my reporting engine from Jasper to Apache™ FOP (Formatting Objects Processor) or any other XML based Reporting Engine.

movies-store.xml

<?xml version="1.0" encoding="utf-8"?>
<store>
	<media>
		<name>Lollywood</name>
		<description>Pakistani film media</description>
			<movies>
				<movie>
					<name>Mola Jutt</name>
					<language>Punjabi</language>
					<starring>
						<cast type="actor">Sultan Rahi</cast>
						<cast type="actor">Najma</cast>
					</starring>
				</movie>
				<movie>
					<name>Wanted</name>
					<language>Urdu</language>
					<starring>
						<cast type="actor">Shan</cast>
						<cast type="actor">Saima</cast>
					</starring>
				</movie>
			</movies>
	</media>
	<media>
		<name>Bollywood</name>
		<description>Indian film media</description>
		<movies>
				<movie>
					<name>Devdaas</name>
					<language>Hindi</language>
					<starring>
						<cast type="actor">Shahrukh Khan</cast>
						<cast type="actor">Madhoori Dixet</cast>
						<cast type="actor">Ashwariya Rai</cast>
					</starring>
				</movie>
				<movie>
					<name>Risk</name>
					<language>Hindi</language>
					<starring>
						<cast type="actor">Mazhar Hassan</cast>
						<cast type="actor">Vinood khana</cast>
					</starring>
				</movie>
			</movies>
	</media>
	<media>
		<name>Hollywood</name>
		<description>English film media</description>
		<movies>
				<movie>
					<name>MI:Ghost Protocol</name>
					<language>English</language>
					<starring>
						<cast type="actor">Tom Crusie</cast>
						<cast type="actor">Gambel</cast>
						<cast type="actor">Tina</cast>
						<cast type="actor">Fahad Shehzad</cast>
					</starring>
				</movie>
				<movie>
					<name>Thor</name>
					<language>English</language>
					<starring>
						<cast type="actor">Mazhar Hassan</cast>
						<cast type="actor">Fahad Shehzad</cast>
						<cast type="actor">Ninja Turtle</cast>
						<cast type="actor">Nargis</cast>
					</starring>
				</movie>
			</movies>
	</media>
</store>

Designing Report in iReport

Now we will run iReport to configure our datasource.

1 - Click on "Report DataSource" button this will bring a popup window "Connections/Datasource".
2 - Click on "New" Button, It will provide a list of type of datasources we can create.
3 - Select "XML file datasource" from list, and click "Next" button
4 - Type "movies xml datasource" in Name field.
5 - XML File: click browse button to select your xml file in our case its "movie-store.xml"
6 - Select radio button for option "Use the report XPath expression when filling the report"
7 - Click "Test" button to check if every thing is fine.
8 - Now Click "Save" button
9 - Now Click "close" button


Now we can see our newly created datasource is slected in top bar drop down list “movies xml datasource”

Configuring XPATH

1 - Now Click on report Query button (near zoom in/out icons on top bar)
2 - This will bring a "Report query" popup window(by default first tab is selected)
3 - Select "XPath" from "Query lanaguge" dropdown box.
4 - In text area type following xpath expression
/store/media

This will selecte all media nodes in your source xml files
5 – exoand media node from treeview on right side
6 – drag and drop name and description fields in Field area.
7 – press OK

Designing Report

1 - Expand "Fields" node in your main "Jasper iReport Designer" screen.
    here we can see our two fields that we have included in previous step
2 - Now simple drag both fields one by one on your report detail section.
3 - Aligh them, style them as per your requriement
4 - just hit the preview button to view your pdf report.

Sub-Report functionality

Now we will come to actual part of the tutorial which actually forced me to write this tutorial as I kept on forgetting how I did this last time.
so no waiting more.

We will extends from report that we have created above.

List Control

1 - Now drag and drop "List" control from "Palatte" view on to your report detail section.
2 - Now Right click "dataset1" and select "Properties"
3 - Rename "dataset1" to "Movies_Dataset" in "Dataset name" Field.(not required but more descriptive)
4 - Type following expression in "Query Text" field.
/store/media/movies/movie
We are doing this because now we want to select all movie nodes for out List control.
5 - Select "xPath" from "The lanaguge for the dataset query" drop down field.
6 - Click "Close" button
7 - Now again reight click on out dataset (now its Movies_Dataset) and select "Edit Query"
Here you will notice that "XPath" is selected in Query lanagueg field, and an xpath expression in text area.
8 - Expand store/media/movies/movie node from treeview on right side.
9 - drag and drop name and languge fields in field area.
10 - Click OK

Using Dataset fields.

1 - Expand "Movies_Dataset" node in main screen of "Jasper iReport Designer".
2 - and then expand "Fields" node
    Here you can see our new fields name and language
3 - Drag and Drop both fields to our List field present on our detail section of the report. (format, align according to your requirement).
4 - now right click on your list control and select "Edit list datasource". It will open "Dataset Run" popup window.
you will notice "Movies_Dataset" is selected for "Sub dataset" field. (if not select it)
5 - In same window in first tab("Connection/Datasource exp") select "Use datasource expression" from dropdown list
6 - In text area type following expression.
$P{REPORT_DATA_SOURCE}.subDataSource("/media/movies/movie")

that is the only trick involved to get sub-report result from List control. the above expression will pass the movie nodes to our list control.
and fields in list control will retrive data from here.


7 – click OK, and hit Preview button to generate pdf report.

Now you can see “media” as Lollywood, bollywood and hollywood, and movies in each list.
Here is my genrated pdf report result.

Mazhar Movie Store
Lollywood
Pakistani film media
Movies
Mola Jutt Punjabi
Wanted Urdu
Bollywood
Indian film media
Movies
Devdass Hindi
Risk Hindi
Hollywood
English film media
Movies
MI: Ghost Protocol English
Thor English

Another level deep – 3rd Level

Ok now we want to show casting of the movie as well which is a 3rd level infomation in our xml data source.

/store/media/movies/movie/starring/cast
1 - Drag another "List" control from "Palette" view and drop on the already added "List" control, that we have added in previous step
	for shoing movie name and languge.
	So this new list will be the child of first list.
2 - As usual a new dataset for the list is created, right click and select "Properties".
3 - Rename this dataset to "Cast_Datasource" in "Dataset name" field.
4 - Type following expression in "Query Text" field.
/store/media/movies/movie/starring/cast

5 – Select “xPath” for “The language for the dataset query” drop down list.
6 – Click close button.
7 – Right Click on “Cast_Datasource” and select “Edit Query”
8 – In new popup window “XPath” will be slected for “Query lanaguge” and you will be able to see query expression as well in textarea
9 – From xml nodes treeview on right exapand nodes to reas “cast”, exapnd it
10 – Drag and Drop “cast” node as well as “type” (attribute) in field list.
11 – Press OK

Now on you main screen of “Jaspersoft iReport designer” you will be able to our new dataset “Cast_Database”.
Expand this node.

1 - Expand "Fields" node in the dataset. (we can see out "cast" and "type" fields)
2 - Now drag and dorop both of them into newly added list (align and format them according to your requirement).
3 - Now right click on this 2nd "List" Control and select "Edit list datasource"
    Make sure "Cast_Datasource" is selcetd in "Sub dataset" field"
4 - In first tab "Connection/Datasource exp", selecet "Use datasource expression"
5 - and type following experssion in text area.
$P{REPORT_DATA_SOURCE}.subDataSource("/movie/starring/cast")

6 – Press OK

We are done here hit preview button to genrate report.
my output looks as follows.

Mazhar Movie Store
Lollywood
Pakistani film media
Movies
Mola Jutt Punjabi
Casting

Sultan Rahi actor
Najma actor
Wanted Urdu
Casting

Shan actor
Saima actor
Bollywood
Indian film media
Movies
Devdass Hindi
Casting

Shahrukh Khan actor
Madhoori Dixet actor
Ashwariya Rai actor
Risk Hindi
Casting

Mazhar Hassan actor
Vinood Khana actor
Hollywood
English film media
Movies
MI: Ghost Protocol English
Casting

Tom Crusie actor
Gambel actor
Tina actor
Fahad Shehzad actor
Thor English
Casting

Mazhar Hassan actor
Fahad Shehzad actor
Ninja Turtule actor
Nargis actor

here is my JRXML file contents.

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="movie_report" language="groovy" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
	<property name="ireport.zoom" value="1.0"/>
	<property name="ireport.x" value="0"/>
	<property name="ireport.y" value="0"/>
	<subDataset name="Movies_Dataset">
		<queryString language="xPath">
			<![CDATA[/store/media/movies/movie]]>
		</queryString>
		<field name="name" class="java.lang.String">
			<fieldDescription><![CDATA[name]]></fieldDescription>
		</field>
		<field name="language" class="java.lang.String">
			<fieldDescription><![CDATA[language]]></fieldDescription>
		</field>
	</subDataset>
	<subDataset name="Cast_Datasource">
		<queryString language="xPath">
			<![CDATA[/store/media/movies/movie/starring/cast]]>
		</queryString>
		<field name="cast" class="java.lang.String">
			<fieldDescription><![CDATA[child::text()]]></fieldDescription>
		</field>
		<field name="type" class="java.lang.String">
			<fieldDescription><![CDATA[@type]]></fieldDescription>
		</field>
	</subDataset>
	<queryString language="xPath">
		<![CDATA[/store/media]]>
	</queryString>
	<field name="name" class="java.lang.String">
		<fieldDescription><![CDATA[name]]></fieldDescription>
	</field>
	<field name="description" class="java.lang.String">
		<fieldDescription><![CDATA[description]]></fieldDescription>
	</field>
	<background>
		<band splitType="Stretch"/>
	</background>
	<title>
		<band height="79" splitType="Stretch">
			<staticText>
				<reportElement x="188" y="26" width="153" height="20"/>
				<textElement>
					<font size="15" isBold="true"/>
				</textElement>
				<text><![CDATA[Mazhar Movie Store]]></text>
			</staticText>
		</band>
	</title>
	<detail>
		<band height="130" splitType="Stretch">
			<textField>
				<reportElement mode="Opaque" x="0" y="0" width="555" height="20" backcolor="#FF0033"/>
				<textElement>
					<font size="14" isBold="true" isItalic="true" isUnderline="true"/>
				</textElement>
				<textFieldExpression class="java.lang.String"><![CDATA[$F{name} + " "]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="76" y="20" width="479" height="19"/>
				<textElement/>
				<textFieldExpression class="java.lang.String"><![CDATA[$F{description}]]></textFieldExpression>
			</textField>
			<componentElement>
				<reportElement mode="Opaque" x="76" y="61" width="479" height="69" backcolor="#99FFFF"/>
				<jr:list xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
					<datasetRun subDataset="Movies_Dataset">
						<dataSourceExpression><![CDATA[$P{REPORT_DATA_SOURCE}.subDataSource("/media/movies/movie")]]></dataSourceExpression>
					</datasetRun>
					<jr:listContents height="69" width="479">
						<textField>
							<reportElement x="53" y="0" width="100" height="20"/>
							<textElement>
								<font size="12" isBold="true" isItalic="true"/>
							</textElement>
							<textFieldExpression class="java.lang.String"><![CDATA[$F{name}+ " "]]></textFieldExpression>
						</textField>
						<textField>
							<reportElement x="249" y="0" width="100" height="20"/>
							<textElement/>
							<textFieldExpression class="java.lang.String"><![CDATA[$F{language}]]></textFieldExpression>
						</textField>
						<componentElement>
							<reportElement mode="Opaque" x="78" y="37" width="389" height="21" backcolor="#FFFFCC"/>
							<jr:list>
								<datasetRun subDataset="Cast_Datasource">
									<dataSourceExpression><![CDATA[$P{REPORT_DATA_SOURCE}.subDataSource("/movie/starring/cast")]]></dataSourceExpression>
								</datasetRun>
								<jr:listContents height="21" width="389">
									<textField>
										<reportElement x="10" y="1" width="100" height="20"/>
										<textElement/>
										<textFieldExpression class="java.lang.String"><![CDATA[$F{cast}]]></textFieldExpression>
									</textField>
									<textField>
										<reportElement x="132" y="1" width="100" height="20"/>
										<textElement/>
										<textFieldExpression class="java.lang.String"><![CDATA[$F{type}]]></textFieldExpression>
									</textField>
								</jr:listContents>
							</jr:list>
						</componentElement>
						<staticText>
							<reportElement x="112" y="17" width="100" height="20"/>
							<textElement>
								<font isBold="true" isUnderline="true"/>
							</textElement>
							<text><![CDATA[Casting ]]></text>
						</staticText>
					</jr:listContents>
				</jr:list>
			</componentElement>
			<staticText>
				<reportElement x="76" y="41" width="100" height="20"/>
				<textElement>
					<font isBold="true" isUnderline="true"/>
				</textElement>
				<text><![CDATA[Movies]]></text>
			</staticText>
		</band>
	</detail>
</jasperReport>




Here I would like to share an example on how to inject javascript into browser, to fill any of the text field value in a form.

<form name="frm1" action="somelink.php" method="get">
<input id='txt1' type="text" value="muhammad mazhar hassan" />
</form>

What you have to do is,write a javaScript code in browser URL box and press enter (but remember the above page must be loaded before you do this step.

first I will access my target page (get loaded in browser)

url: http://localhost/inject/testpage.html

now I can see a text box in browser with a value in it

muhammad mazhar hassan

In order to replace above value, I will paste following code, in browser’s URL(replace existing url link)

javascript:void(document.frm1.txt1.value = 'papai chullo')

after you press enter you will see that the value of text box has been changed.

papai chullo

Cheers! G-o-Jutta





I always wondered how to write a single query, which can retrieve all parents (nested) of any particular category

Table structure

for example if I provide idCategory=8 which is  “black”, it should return some thing like

6,4,2,1 which is (Jeans->Trouser->Mens Wear-> Clothes)

but unfortunately I am unable to write such query, so I decided to write a stored procedure or a function that full fill the purpose. both options were open, so I started with stored procedure(as debugging is easy compared to function) and finally converted it to function to full fill my requirements.

Note: There are 2 ways to do it, first one is to use Recursive one, which is easy to code/write and second one is iterative way, so I decided the 2nd method.

This stored procedure takes 2 parameters
1st is the id of the category
2nd is the maximum depth level, there are chances that we might have a bug or some thing in our code and procedure get stuck in infinite loop or there is also possibility there is a circular loop of categories. (like A is parent of B, B is parent of C, and C is parent of A)  A->B->C->A

so 2nd parameter will check the maximum allowed iteration.

here is procedure

DROP PROCEDURE IF EXISTS getAllParentCategories;
CREATE PROCEDURE `getAllParentCategories`( IN idCat int, IN intMaxDepth int)
BEGIN
DECLARE chrProcessed TEXT;
DECLARE quit INT DEFAULT 0;
DECLARE done INT DEFAULT 0;
DECLARE Level INT DEFAULT 0;
DECLARE idFetchedCategory INT;
DECLARE chrSameLevelParents VARCHAR(255);
DECLARE chrFullReturn VARCHAR(255);
DECLARE cur1 CURSOR FOR SELECT idParentCategory FROM tbl_categories WHERE idCategory IN (@param);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

SET chrFullReturn = '';
SET @param = idCat;
set chrProcessed = concat('|',idCat, '|');
myloop:LOOP
      IF quit = 1 THEN
        leave myloop;
      END IF;

      OPEN cur1;

      SET chrSameLevelParents = '';
      FETCH cur1 INTO idFetchedCategory;
      while(not done) do
          SET Level = Level + 1;
          IF idFetchedCategory > 0 THEN

                if NOT INSTR(chrProcessed,concat('|',idFetchedCategory, '|')) > 0 THEN
                      if CHAR_LENGTH(chrSameLevelParents) > 0 then
                        set chrSameLevelParents = concat( idFetchedCategory, ',', chrSameLevelParents );
                      else
                        set chrSameLevelParents = idFetchedCategory;
                      end if;

                      set chrProcessed = concat('|',idFetchedCategory, '|', chrProcessed );
                 end if;

           END IF;
           FETCH cur1 INTO idFetchedCategory;

      end while;
      CLOSE cur1;

      IF Level > intMaxDepth THEN SET done =1; SET quit = 1; END IF;

      if CHAR_LENGTH(chrSameLevelParents) > 0 THEN
        if CHAR_LENGTH(chrFullReturn) > 0 THEN
            set chrFullReturn = concat( chrFullReturn, ',', chrSameLevelParents );
        ELSE
            set chrFullReturn = chrSameLevelParents;
        END IF;

        SET @param = chrSameLevelParents;
        SET chrSameLevelParents = '';
        SET done = 0;

      ELSE
        SET quit = 1;
      END IF;
END LOOP;

SELECT Level,chrFullReturn;

END;

Now we will call this function as follows

call getAllParentCategories(8 ,100);

8 is idCategory of “Black” and 100 is max depth.
result set will look like as follows

Level chrFullReturn
5 6,4,2,1

Here problem is chrFullReturn is text value and will not produce any use full result however if this procedure is called from any programming language then we can use this result in another query to get categories name.

or we can replace following query with prepare statement to retrieve proper result set.

SELECT Level,chrFullReturn;

replace with

SET @strQuery = concat('SELECT idCategory, CategoryName FROM tbl_categories WHERE idCategory IN (',chrFullReturn,')'); PREPARE stmt1 FROM @strQuery;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;

Now it will return proper and useful result set.

idCategory CategoryName
1 Clothes
2 Mens Wear
4 Trouser
6 Jeans




I always ask my friend(Faisal Mahmood) about this query and next time I forget the query, so he advised me to write it down and do not ask him again, so I decided to write it for everyone ;).
In order to list all stored procedure/functions in any database use following MySQL command

select * from information_schema.ROUTINES
where routine_schema = 'your_db_name'

For only names use following command.

select routine_name from information_schema.ROUTINES
where routine_schema = 'your_db_name'