Sunday, January 31, 2010

The Chain Of Responsibility Pattern

Today, in this blog post, I am going to discuss about the chain of responsibility pattern. As the name suggests, the pattern deals with a chain of objects where each object is aware of the next object that needs to be called.

Lets see where this pattern can be used.

  1. When your request contains data that needs to be processed by different objects where each object deals with different parts of the requests.
  2. When your request contains data that needs to be processed at several levels and processing can be halted at any of the levels.
  3. When your request needs to be modified before reaching its final destination.


Lets elaborate on the concept using an example.

Scenario :

I will try to explain this pattern as well by taking an example of a game as I have been doing in my previous posts. Lets assume that we have a game with two players. Each player can attack the other player. When a playerq attacks player2 and vice versa, the victim player's health is reduced. Now the game isin't much fun until you have some extra features like a  'Shield' to protect the players.
Now suppose player1 has a shield that can absorb 30 percent of the damage of the attack. And player 2 has a Shield that can absorb 70 percent of the damage of the attack. But when a player attacks another player, how will the damage be absorbed by the shield??

So, here are our requirements.

  1. A player is not aware of the properties of the shield that protects him.
  2. A player is not aware of the number of shields that protect him.
  3. A player is not aware of the shields that protect the other player.
  4. A shield can be attached to any player.
  5. A shield absorbs the damage to the level set by its configuration.
  6. A shield is not aware whether the next object that will absorb the remaining damage is a shield or a player.


So, we have a candidate for the Chain of responsibility pattern.

Using the chain of responsibility pattern to solve the scenario

In this scenario, in order to implement the chain of responsibility pattern, we are going to create an interface called 'Damageable'. The interface declares a function - int absorb(int damageValue). The purpose of the function is to absorb a damage and return the damage that could not be absorbed. Both our Player class and our Shield class implement this interface and hence both of them are Damageable objects. The player class saves as its instance variable, the next damageable object to which it can pass on the damage before it can process the damage itself. The shild object also stores a similar variable in its instance variable the informs it of the next object in the chain that can absorb the damage. In the 'absorb' method of the Player class, the player checks if there is any damageable object in its chain that can process the damage. If there is such an object, the player delegates the process of absorbing the damage to the next damageable object in the chain. This continues until the chain returns with the actual value of the damage that can be processed by the player, for which the player calls the 'reduceHealth' method.

The following code example demonstrates an implementation of the above scenario using the chain of responsibility pattern in Java.

Damageable.java

public interface Damageable {
    //Returns the damageValue that it could not absorb.
    public int absorb(int damageValue);
}


Player.java

public class Player implements Damageable{
    private int health;
    private Damageable nextDamageableObject;
    private String name;

    public Player() {
        health=100;
    }

    public int reduceHealth(int value) {
        System.out.println("Health Before Reducing : "+ health);
        if(value<=health)
        {
            health-=value;
            value=0;
        }
        System.out.println("Health After Reducing : "+ health);
        return value;
    }

    public int getHealth() {
        return health;
    }

    public void setHealth(int health) {
        this.health = health;
    }

    public void setNextDamageableObject(Damageable nextDamageableObject) {
        this.nextDamageableObject = nextDamageableObject;
    }

    public Damageable getNextDamageableObject() {
        return nextDamageableObject;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    
    public int absorb(int damageValue) {
        if(nextDamageableObject!=null)
        {
            damageValue = nextDamageableObject.absorb(damageValue);
        }
        //After all the damageable objects have absorbed the damage,
        //reduce the player's health by the specified amount
        System.out.println("Finaly Attempting To Reduce "+ this.getName() + "'s health by "+damageValue);
        return reduceHealth(damageValue);
    }


    public void attack(Player p,int damageValue)
    {
        p.absorb(damageValue);
    }
}
Shield.java
public class Shield implements Damageable{
    private int damageAbsorbPercent;
    private Damageable nextDamageableObject;
    private String name;

    public Shield(int damageAbsorbPercent, Damageable nextDamageableObject, String name) {
        this.damageAbsorbPercent = damageAbsorbPercent;
        this.nextDamageableObject = nextDamageableObject;
        this.name = name;
    }

    
    public int getDamageAbsorbPercent() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public Damageable getNextDamageableObject() {
        return nextDamageableObject;
    }

    public void setNextDamageableObject(Damageable nextDamageableObject) {
        this.nextDamageableObject = nextDamageableObject;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    

    public int absorb(int damageValue) {
        int absobedValue = (damageValue* damageAbsorbPercent)/100;
        damageValue = damageValue-absobedValue;
        System.out.println(this.name + " absorbed damage % (" + damageAbsorbPercent +")");
        
        //The shield passes on the damage to the next damageable object in the chain.
        if(nextDamageableObject!=null)
        {
            damageValue = nextDamageableObject.absorb(damageValue);
        }
        return damageValue;
    }
}
Game.java
public class Game {
    private Player player1;
    private Player player2;

    public Game() {
    }

    public Player getPlayer1() {
        return player1;
    }

    public void setPlayer1(Player player1) {
        this.player1 = player1;
    }

    public Player getPlayer2() {
        return player2;
    }

    public void setPlayer2(Player player2) {
        this.player2 = player2;
    }
    
}
Main.java
public class Main {
    public static void main(String[] args)
    {
        Game game=new Game();
        Player player1 = new Player();
        Player player2 = new Player();

        player1.setName("Player 1");
        player2.setName("Player 2");

        Shield s1=new Shield(30, null, "Normal Shield1");
        Shield s2=new Shield(70, null, "Power Shield");

        player1.setNextDamageableObject(s1);
        player2.setNextDamageableObject(s2);

        player1.attack(player2, 30);
        System.out.println("\n");
        player2.attack(player1, 30);


        //Now add another shiled to the player1
        Shield s3=new Shield(30, player1.getNextDamageableObject(), "Normal Shield2");
        player1.setNextDamageableObject(s3);
        System.out.println("\nAdded Another Shiled to player1 which absorbs 30 percent damage");

        player1.attack(player2, 30);
        System.out.println("\n");
        player2.attack(player1, 30);
    }
}

Following is the output that I get on my console when I run the main program.

Power Shield absorbed damage % (70)
Finaly Attempting To Reduce Player 2's health by 9
Health Before Reducing : 100
Health After Reducing : 91


Normal Shield1 absorbed damage % (30)
Finaly Attempting To Reduce Player 1's health by 21
Health Before Reducing : 100
Health After Reducing : 79

Added Another Shiled to player1 which absorbs 30 percent damage
Power Shield absorbed damage % (70)
Finaly Attempting To Reduce Player 2's health by 9
Health Before Reducing : 91
Health After Reducing : 82


Normal Shield2 absorbed damage % (30)
Normal Shield1 absorbed damage % (30)
Finaly Attempting To Reduce Player 1's health by 15
Health Before Reducing : 79
Health After Reducing : 64


Signing Off
Ryan

Saturday, January 30, 2010

The Command Pattern

Today, in this post I am going tot talk about the command pattern and implement it in Java. The command pattern is a behavioral pattern whose primary objective is to decouple the sender from the receiver in such a way that the sender is not even aware of the type of the receiver of the command.

So, lets see where this pattern can be used.

The command pattern can be used in situations where you need a perform a given task on a number of objects of different types. But in each of these objects, not only is the implementation dependent on the type of the object, but also the functionality is completely different from the other objects.

Lets illustrate with the help of an example.

Sample Scenario :

As in my other posts, I will try to explain the scenario by means of examples of a game.
I believe that many of us have played First Person Shooter(FPS) games where you go on a mission and clear each level by destroying several enemies by using ruthless gunpower (and sometimes good strategies as well). One thing that is common among most of the FPS is that you have a number of weapons and each one of them has a primary attack and a secondary attack. The primary attack and secondary attack are characteristic features of that specific weapon. But when you fire the weapon, all you do is click your left mouse button for primary attack and click your right mouse button for secondary attack. What happens when you click on the left/right mouse button is something that is weapon specific.

Now, lets map this scenario to the command pattern. The following requirements are clearly visible from the situation.
  1. The client(yourself), issues two types of commands - primary attack, secondary attack.
  2. Each weapon has different types of attack mechanisms that it can perform.
  3. For each weapon, you need to associate your primary attack and secondary attack to one of the predefined attack mechanisms of your weapon.

You need to decouple the sender's commands i.e. the primary attack and secondary attack command from knowing the actual attack mechanism being executed. This gives you the ability to associate the primary attack command with a different mechanism in the future. for example, if the user chooses to make his left click function as the right click and the right click function as the left click.

Here is a sample description of my game components.
I have 2 weapons in my game. The Plasma Gun and the Shotgun. The Plasma Gun has 2 modes of attack - normal fire and blast fire. The Shotgun has 2 modes of attack - Single shot attack, and dual shot attack. Initially, what I want to do is to make one of these mechanisms the primary attack and secondary attack for each weapon.

Let's see how this could have been done without the command pattern and the problems that would arise.

Firstly, you would declare a base class called Weapon, that would have 2 functions- primary attack and secondary attack. Then, you would subclass the Weapon class and create 2 new classes - Shotgun and PlasmaGun that would override the primary attack and secondary attack functions. Your client would create objects of the weapons and call the primary attack and secondary attack functions on the objects and the code for your weapon specific functionality would execute.

That's pretty simple eh?

Oh, but wait! What if I want to swap my mouse functions?? i.e. The left click becomes the right click? Or what if one fine day in the future I decide that each gun has 5 attack mechanisms, but the user has to select which mechanism can be activated by which input- right click or left click. Os suppose you have added a new  gun with a new attack mechanism and want to associate it with the middle click. What will you do then?? Will you add new methods to your Weapon class?? Will you use several boolean flags to determine what function will be called when? Or worse of all, will you resort to complex techniques such as reflection?

The issue here is that you certainly don't want your client want to know what changes have been made at the level of your Weapon classes. And also, you don't want your classes to be aware of the type of command issued by the client. i.e. the weapons should not be aware whether the client is issuing a primary attack command or a secondary attack command.

The Command Pattern to the rescue!

The command pattern decouples the client from the destination by acting as a middleman and converting the client request to the appropriate destination request. In the code that follows, I will demonstrate how to achieve this functionality. Lets first discuss what the code will do.

Firstly, I will create my Shotgun and PlasmaGun classes without the need of implementing any superclasses or superinterfaces for this scenario. The Shotgun class will have 2 mehtods- one to fire a single shot, and another to fire a dual shot. Similarly the PlasmaGun will have 2 methods - One for normal fire and the other for a blast fire. These classes are not aware of the concept of a primary attack and secondary attack.

Now, I will create a Command interface that has one method- execute(). Then I create classes that implement the Command interface, one class for each command issued to a gun. i.e. Primary/Seconday Attack for shotgun, and primary/seconday attack for PlasmaGun. So, 4 command classes. All these command classes have a private instance of the gun over which they will execute. In the execute function, we will call the appropriate function of the gun classes.

The beauty of this approach is that the Gun classes do not know what is a primary or a secondary attack, and the client does not need to know what is the exact method that will be called when is issues the primary and secondary attack command.

The problem with this approach is that the for each type of command, we will have to create new command classes. This can considerably increase the classes that you may need to manage and can become a problem if you have several such functionalities, However, being a design pattern, it is not bound to suit the requirement for all scenarios. So, its up to u to decide when and where the command pattern will be useful in your project.

Following is the implementation of the above scenario using the Command pattern in Java.


PlasmaGun.java

public class PlasmaGun {
    public boolean firePlasmaShot()
    {
        System.out.println("Plasma Fire : Normal");
        return true;
    }

    public boolean firePlasmaBlast()
    {
        System.out.println("Plasma Fire : Blast");
        return true;
    }
}


ShotGun.java

public class ShotGun {

    public boolean fireSingleShot() {
        System.out.println("ShotGun Fire : Single");
        return true;
    }

    public boolean fireTripleShot() {
        System.out.println("ShotGun Fire : Triple");
        return true;
    }
}


Command.java

public interface Command {
    public void execute();
}



PlasmaGunNormalFireCommand.java

public class PlasmaGunNormalFireCommand implements Command{
    private PlasmaGun gun;

    public PlasmaGunNormalFireCommand(PlasmaGun gun) {
        this.gun = gun;
    }

    public void execute() {
        gun.firePlasmaShot();
    }
}



PlasmaGunBlastFireCommand.java

public class PlasmaGunBlastFireCommand implements Command{
    private PlasmaGun gun;

    public PlasmaGunBlastFireCommand(PlasmaGun gun) {
        this.gun = gun;
    }

    public void execute() {
        gun.firePlasmaBlast();
    }
}



ShotGunSingleShotCommand.java

public class ShotGunSingleShotCommand implements Command{
    private ShotGun gun;

    public ShotGunSingleShotCommand(ShotGun gun) {
        this.gun = gun;
    }

    public void execute() {
        gun.fireSingleShot();
    }
}



ShotGunTripleShotCommand.java

public class ShotGunTripleShotCommand implements Command{
    private ShotGun gun;

    public ShotGunTripleShotCommand(ShotGun gun) {
        this.gun = gun;
    }

    public void execute() {
        gun.fireTripleShot();
    }
}



WeaponControl.java


public class WeaponControl {
    private Command primaryAttackCommand, secondaryAttackCommand;

    public WeaponControl(Command primaryAttackCommand, Command secondaryAttackCommand) {
        this.primaryAttackCommand = primaryAttackCommand;
        this.secondaryAttackCommand = secondaryAttackCommand;
    }

    public void primaryAttack()
    {
        primaryAttackCommand.execute();
    }

    public void secondaryAttack()
    {
        secondaryAttackCommand.execute();
    }
}


Main.java

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        ShotGun sg=new ShotGun();
        ShotGunSingleShotCommand sgSingleShotCmd= new ShotGunSingleShotCommand(sg);
        ShotGunTripleShotCommand sgTripleShotCmd = new ShotGunTripleShotCommand(sg);

        PlasmaGun pg=new PlasmaGun();
        PlasmaGunNormalFireCommand pgNormalFireCmd= new PlasmaGunNormalFireCommand(pg);
        PlasmaGunBlastFireCommand pgBlastFireCmd = new PlasmaGunBlastFireCommand(pg);

        WeaponControl shotGunControl=new WeaponControl(sgSingleShotCmd, sgTripleShotCmd);
        WeaponControl plasmaGunControl=new WeaponControl(pgNormalFireCmd, pgBlastFireCmd);

        shotGunControl.primaryAttack();
        plasmaGunControl.secondaryAttack();

        shotGunControl.secondaryAttack();
        plasmaGunControl.primaryAttack();

    }

}


Signing Off
Ryan

Thursday, January 28, 2010

The Visitor Pattern

The visitor pattern is one of those patterns that seems to be quite perplexing in the beginning, but is quite useful as well. It took me the longest to understand this pattern as compared to others, mainly because of the drawbacks that this pattern has and due to the various ways in which it can be implemented. In this post, I will try to keep things simple and implement it in a way that I feel, will make it easier to understand.

Let's first see where this pattern can be used.
Suppose that you have a class that for which you have already defined a number of methods. But you observe that similar methods exist in other classes as well, but with subtle differences. Usually, this can be implemented by means of inheritance wherein you keep the common functionality in the superclass and override the necessary methods only in cases where you need to.

Now suppose you already have a set if similar classes. But due to some business requirement, you need to add a certain set of functionality to all those classes. What would you do in the normal approach? Add a method to each of those classes? Ok, you would. But suppose, such requirements keep coming and these requirements are not intended to be permanent. For example, suppose you need a given functionality in the current release of your product, but somehow, you don't feel the need to have that functionality to become the core part of your classes because in the next release, they might become irrelevant.

In my opinion, the Visitor pattern lets you create a fall back mechanism in your classes for exactly the above mentioned scenario. Following are the steps that you can follow :


  1. Declare your class to implement a Visitable interface and implement a method in your classses that accepts a Visitor as an argument.
  2. Create concrete Visitor class that knows about group of classes for which it has to provide the new functionality. It does this by declaring overloaded methods, having the same name but taking in arguments that correspond to the classes for which you want to add the functionality.
  3. In the visitor method of your class, dispatch control to the appropriate method of your visitor class by passing 'this' as the argument. Or you can also pass control to the visitor class, which determines which method needs to be called based upon the type of argument it receives


Lets see an example.

Scenario :
I have a game which has a player. A player can carry 2 weapons. A player can accumulate points in a game. I have 2 types of weapons - ShotGun and a MagicWand. Every weapon has a primary and a secondary attack mechanism which is implemented by each weapon in a weapon specific way. A Shotgun's secondary attack is can be enabled or disabled at any point in the game by setting a boolean property on the Shotgun. A MagicWand has a power level which can be increased/decreased as the game progresses.

Now suppose that you have made all the remaining components of the game. And the game is functioning. Now, all of a sudden, you wake up one morning and decide to add three new features to your game:

  • The shotgun's secondary attack is enabled when the player reaches level 2 or higher
  • The MagicWand's power level is increased by 2 points at the beginning of each level.
  • The player is to be given level clearance bonus points at each level.


So, how do you implement it??

Approach 1 : The normal approach
Create a method called upgrade(int level) in your Player and Weapon class. Override the upgrade in the subclasses to upgrade the specific weapons. The problem with this approach is that for each such new business requirement, you will end up expanding the functionality of your core classes. However the inherent simplicity of this technique will play a vital role in choosing this technique. I believe that one can prefer this technique over the Visitor Pattern Based approach especially if the classes will require the functionality as a core functionality. But if thats not the case, then you certainly don't want to clutter your classes with business logic.

Approach 2 : Helper classes
This approach is pretty obvious. Create a helper class that does all the dirty work for you. You can implement it in any way you find suitable. I am not going to elaborate on this because the possibilities are far too many to be discussed here. So, that's left completely up to you.

Approach 3 : Visitor Pattern
This is by far the most complicated approach of the three approaches, but all the more extensible. In the following examples, observe carefully how I try to use the Visitor Pattern to implement the business requirement of my scenario. There are two core interfaces. One is the Visitor interface, that declares a single method called visit(Visitable visitable). The other is the Visitable interface that declares an accept(Visitor visitor) method. The classes of my domain, namely Player and Weapon, implement this interface. When a Visitable object is visited by a visitor, it accepts it and gives control to the visitor to execute the new functionality for that object by passing itself as an argument to the visit method of the visitor. My concrete visitor class is the LevelUpgradeVsitor that will provide the functionality to upgrade the objects passed to it.
Enough with that talking. Lets see some code now babay..

Visitor.java

public interface Visitor {
    public void visit(Visitable visitable);
}


Visitable.java

public interface Visitable {
    public void accept(Visitor visitor);
}

Weapon.java

public interface Weapon extends Visitable{
    public void primaryAttack();
    public void secondaryAttack();
}

Player.java

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author ryan
 */
public class Player implements Visitable{
    private List <Weapon> weapons;
    private int points;

    public Player()
    {
        weapons=new ArrayList <Weapon>();
    }

    public List <Weapon> getWeapons() {
        return weapons;
    }

    public void setWeapons(List <Weapon> weapons) {
        this.weapons = weapons;
    }

    public boolean addWeapon(Weapon w)
    {
        weapons.add(w);
        return true;
    }

    public int getPoints() {
        return points;
    }

    public void setPoints(int points) {
        this.points = points;
    }

    public void accept(Visitor visitor) {
        visitor.visit(this);
        
        for(Weapon w: weapons)
        {
            w.accept(visitor);
        }
    }

}

ShotGun.java

public class ShotGun implements Weapon{

    private boolean dualShotEnabled;

    public ShotGun()
    {
        dualShotEnabled=false;
    }

    public void setDualShotEnabled(boolean dualShotEnabled) {
        this.dualShotEnabled = dualShotEnabled;
    }

    public boolean isDualShotEnabled() {
        return dualShotEnabled;
    }
    

    public void primaryAttack() {
        System.out.println("ShotGun : SingleShot");
    }

    public void secondaryAttack() {
        if(dualShotEnabled)
        {
            System.out.println("ShotGun : DualShot");
        }
    }

    public void accept(Visitor visitor) {
        
        visitor.visit(this);
    }

}


MagicWand.java

public class MagicWand implements Weapon{
    private int powerLevel;

    public void setPowerLevel(int powerLevel) {
        this.powerLevel = powerLevel;
    }

    public int getPowerLevel() {
        return powerLevel;
    }
    

    public void primaryAttack() {
        System.out.println("Magic Wand(Power level : "+powerLevel+") : Primary Attack.");
    }

    public void secondaryAttack() {
        System.out.println("Magic Wand(Power level : "+powerLevel+") : Secondary Attack.");
    }

    public void accept(Visitor visitor) {
        visitor.visit(this);
    }
}

LevelUpgradeVisitor.java -- The implementation of the Visitor Pattern. You can have many such visitors based upon different business requirements.

public class LevelUpgradeVisitor implements Visitor{

    private int level;

    public int getLevel() {
        return level;
    }

    public void setLevel(int level) {
        this.level = level;
    }
    
    public void visit(Visitable visitable) {
        
        if(visitable instanceof Player)
        {
            upgrade((Player)visitable);
            System.out.println("Player Upgraded");
        }
        else
        {
            
            if(visitable instanceof ShotGun)
            {
                upgrade((ShotGun)visitable);
                System.out.println("ShotGun Upgraded");
            }
            else
            {
                
                if(visitable instanceof MagicWand)
                {
                    upgrade((MagicWand)visitable);
                    System.out.println("MagicWand Upgraded");
                }
            }
        }
    }

    public void upgrade(Player p)
    {
        int bonus=level*100;
        System.out.println("Adding Level Bonus For Player : "+ bonus);
        p.setPoints(p.getPoints()+bonus);
    }

    public void upgrade(ShotGun s)
    {
        if(level>=2)
        {
            s.setDualShotEnabled(true);
        }
    }

    public void upgrade(MagicWand m)
    {
        if(level>=2)
        {
            m.setPowerLevel(m.getPowerLevel()+2);
        }
    }
}

Game.java

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author ryan
 */
public class Game implements Visitable{
    private Player player1;
    private int level;
    
    public Game() {}


    public Player getPlayer1() {
        return player1;
    }

    public int getLevel() {
        return level;
    }

    public void setLevel(int level) {
        this.level = level;
    }

    
    public void setPlayer1(Player player1) {
        this.player1 = player1;
    }

    public void accept(Visitor visitor) {
        visitor.visit(this);
        player1.accept(visitor);
    }

}


Main.java

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        Game game=new Game();
        LevelUpgradeVisitor luv = new LevelUpgradeVisitor();

        Player p=new Player();
        ShotGun sg=new ShotGun();
        MagicWand mw= new MagicWand();
        

        //Initialize the Player's values
        p.setPoints(10);
        p.addWeapon(sg);
        p.addWeapon(mw);

     
        //Lets Initialize the game.
        game.setPlayer1(p);
        game.setLevel(1);

        
        
        System.out.println("Before Level Upgrade");
        System.out.println("Initial Level "+game.getLevel());
        System.out.println("Initial Player Points : " + game.getPlayer1().getPoints());
        game.getPlayer1().getWeapons().get(0).primaryAttack();
        game.getPlayer1().getWeapons().get(0).secondaryAttack();
        game.getPlayer1().getWeapons().get(1).primaryAttack();
        game.getPlayer1().getWeapons().get(1).secondaryAttack();



        //Upgrade Level
        game.setLevel(2);
        luv.setLevel(game.getLevel());
        game.accept(luv);


        System.out.println("\n\nAfter Level Upgrade");
        System.out.println("New Level "+game.getLevel());
        System.out.println("New Player Points : " + game.getPlayer1().getPoints());
        game.getPlayer1().getWeapons().get(0).primaryAttack();
        game.getPlayer1().getWeapons().get(0).secondaryAttack();
        game.getPlayer1().getWeapons().get(1).primaryAttack();
        game.getPlayer1().getWeapons().get(1).secondaryAttack();


    }

}



Please not that in in order to keep things simple, I have used a simple if-else structure to determine the appropriate method to be invoked. This could also have been done using reflection in fewer lines of code. But  I thought it would unnecessarily complicate things for an introductory article as our motive here is to learn about the pattern rather that learn about the pros and cons of using reflection to implement this pattern. If you have better ideas to implement this scenario using this patter, please comment. I'd love to learn a new way to do stuff. But I sincerely hope that the example is lucid enough to help you understand the objective of this pattern. Cheers!


Signing Off
Ryan

Tuesday, January 26, 2010

The Decorator Pattern

Patterns.. Patterns.. Patterns! Patterns have become something that surround us everywhere. Well, not everywhere in the real world, but definitely so in the world of Programing Languages.

Today, in this post, I am going to write about the Decorator Pattern. And of course, i will implement it in source code using Java. Doing a simple search on Google tells you that one of the best examples of this pattern's implementation is the classes of the package java.io. BufferedReader, BufferedWriter, FileReader, FileWriter etc etc, are all examples of using the decorator pattern.

So, What is the decorator pattern?
The decorator pattern, as its name suggests, is a pattern that lets you decorate an 'object' by adding or removing certain features. Note that I emphasize the word 'object'. Lets see why.

I assume that the reader of this post is aware of the concept of inheritance and its implementation in Java.

Now lets illustrate the concept by an example. Most of us might have played computer games ryt? There are many games that let 2 or more players play at the same time against several computer players(called Bots). Bots are similar to computer players, but they differ in the way they play because the computer handles their gameplay. And most of the times, we find that bots have a few different features as compared to human players.For example, a bot has a skill level/difficulty level, whereas a human player may have experience points. And both might have common features 'health' etc etc.

So, if we were to model this scenario using OOPS, one possible way would be to create a base class called Player with attributes common to all Player's like 'health', and functions like 'play()' and 'reduceHealth(). Now we can have a class called 'HumanPlayer' that extends the Player class and adds features like 'experience points', overrides the play() method and the reduceHealth() method.

We can also have a class 'Bot' that extends the 'Player' class that overrides the play() and reduceHealth() functions and attributes like skillLevel.

We can have a Game class that has a list of players, and a list of Bots.

Its pretty simple till now ryt? The game begins by initializing the player list with player objects and the Bot list with Bot objects. Everyone plays and everyone is happy.

But if games were so simple, they wouldn't be so much fun now, would they? Lets try do add a new feature to our game. Lets suppose that when a human player interacts with a certain object in the game landscape, he becomes a power player such that for any kind of attack that he receives by the bots, his health is reduced by only 1 unit instead of being reduced by several units and inflicted by the bots. (Note : The game is responsible for handling the duration of the powerplay.)

Now, there are 2 approaches to implement this feature.



  1. The Normal Approach : Subclass the HumanPlayer class and override the reduceHealth() method in the subclass. When the player in the game ineracts with the object that gives him a power play, create a new object of this subclass, and initialize it with the values in the already existing HumanPlayer object and use this new subclassed object in your game.

    Now, the problem with this approach is that when you create a subclass for a given scenario, you are adding another node in the inheritance hierarchy that lets you create a whole new bunch of objects that behave differently for a given scenario. Suppose you have 20 such scenarios, you will have to create 20 subclasses in the hierarchy just to give 20 different powers to your Human players. This doesn't make much sense when you realize that you will always be using the features of the already existing HumanPlayer in your game for each subclassed object that you create. Waste of precious memory? Ya, you guessed right. So, what do we do? This is where the decorator pattern comes to the rescue.

  2. The Decorator Pattern Approach : If we observe the requirements carefully, we can see that the what we actually need to do is to decorate the player, who has managed to get a power play by interacting with a game object; with a differently implementation of the reduceHealth() method. Notice that I only need to decorate a single object at runtime, the object that will use power play.

    So, what we need to do is to create a new class called PowerPlayer that subclasses the Player class and overrides the implementation of the reduceHealth() for the power play mode. This class is initialized with an instance of a Player to which it delegates other responsibilities.

    Note that we can also choose to subclass the HumanPlayer class. But that can create a restriction in the game when in the future, you decide to enable even bots to have a power play. In that case you would have to duplicate the reduceHealth() code for the Bot.

    Maybe you never want to do such a thing. Maybe you might have to. The decision of the class that you choose to subclass is a design decision and is based upon your foresight and requirements.

    Since this is just an example, and in order to keep it simple, I will subclass the HumanPlayer.

    By subclassing the HumanPlayer, now what I can have in my game is a feature that allows several HumanPlayer objects to coexist but only a single HumanPlayer object to be a power player as determined by the game. Had I chosen to subclass the Player class, I could have had any player- bots or human players, to be able to possess a power play feature by 'decorating' selected player objects with the PowerPlay feature.


Here is the implementation. The only difference here is that I am going to have only one player and several bots, just to keep it simple and not confuse game logic with the logic of implementing the decorator class. The PowerPlayer is my decorator class in this example. But please note that this is only a demonstration of concepet. And it might not be feasible in all situations to apply this pattern. Nor is it an example of how one should implement this in a game. So, just read the code, and have some fun enjoying the beauty of the Decorator pattern.

Player.java

public abstract class Player{
    private int health;

    public abstract boolean play();
    public boolean reduceHealth(int value) {
        health-=value;
        System.out.println("Health reduced By : "+ value);
        return true;
    }

    public int getHealth() {
        return health;
    }

    public void setHealth(int health) {
        this.health = health;
    }
}


Bot.java

public class Bot extends Player{

    private int skillLevel;

    @Override
    public boolean play() {
        System.out.println("Bot (With Skill Level : "+ skillLevel + ") Is Ready To Play");
        //Code that implements how a bot plays
        return true;
    }

    public int getSkillLevel() {
        return skillLevel;
    }

    public void setSkillLevel(int skillLevel) {
        this.skillLevel = skillLevel;
    }

    @Override
    public boolean reduceHealth(int value) {
        //The health of bots reduces slowly as compared to players.
        setHealth(getHealth()-(value-1));
        System.out.println("Health reduced By : "+ value);
        return true;
    }

    public boolean attackPlayer(Player p,int healthReductionValue)
    {
        p.reduceHealth(healthReductionValue);
        return true;
    }
}


HumanPlayer.java

public class HumanPlayer extends Player{
    private int experiencePoints;
    

    public int getExperiencePoints() {
        return experiencePoints;
    }

    public void setExperiencePoints(int experiencePoints) {
        this.experiencePoints = experiencePoints;
    }

    
    
    @Override
    public boolean play() {
        System.out.println("Player (With Experience Points : "+ experiencePoints + ") Is Ready To Play");
        //Code that implements how a human player plays
        return true;
    }

    @Override
    public boolean reduceHealth(int value) {
        setHealth(getHealth()-value);
        System.out.println("Health reduced By : "+ value);
        return true;
    }
}


PowerPlayer.java -- The Decorator Class

public class PowerPlayer extends HumanPlayer{
    private HumanPlayer player;

    public PowerPlayer(HumanPlayer player) {
        this.player = player;
    }

    
    @Override
    public boolean play() {
        System.out.println("Power Player");
        player.play();
        return true;
    }

    @Override
    public boolean reduceHealth(int value) {
        //Power Player's health reduces very slowly
        value=1;
        System.out.println("Setting Health Reduction Value To : "+ value);
        player.reduceHealth(value);
        return true;
    }

    public Player getPlayer() {
        return player;
    }

}


Game.java


public class Game {
    private Player player1;
    private List <Bot> bots;

    public Game() {
        bots=new ArrayList();
    }


    public Player getPlayer1() {
        return player1;
    }

    public void setPlayer1(Player player1) {
        this.player1 = player1;
    }

    public List <Bot> getBots() {
        return bots;
    }

    public void setBots(List <Bot> bots) {
        this.bots = bots;
    }
    
    public void addBots(Bot bot) {
        bots.add(bot);
    }

}


Main.java


public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        Game game=new Game();
        HumanPlayer hp=new HumanPlayer();
        Bot b1=new Bot();
        Bot b2=new Bot();

        //Initialize the Player's values
        hp.setExperiencePoints(10);
        hp.setHealth(100);

        //Initialize the bots values.
        //b1 is a powerful bot because it has a high skill level
        b1.setHealth(100);
        b1.setSkillLevel(10);

        //b2 is a weak bot because it has a low skill level
        b1.setHealth(100);
        b2.setSkillLevel(5);

        //Lets Start the game.
        game.setPlayer1(hp);
        game.addBots(b1);
        game.addBots(b2);
        hp.play();
        b1.play();
        b2.play();

        System.out.println("Initial Player Health : " + game.getPlayer1().getHealth());

        //Let him take a few attacks by the bots
        b1.attackPlayer(game.getPlayer1(), 8);
        b1.attackPlayer(game.getPlayer1(), 4);

        System.out.println("Player Health : " + game.getPlayer1().getHealth());


        
        //Now suppose the player picks up an artifact that
        //allows him to become a power player
        //Note that this Power Play option should be available for a
        //fixed duration, determined by the game. e.g. 30 seconds
        //This is how it 'can' be implemented
        System.out.println("\nStarting Power Play Mode");
        PowerPlayer pp=new PowerPlayer(hp);
        game.setPlayer1(pp);

        //Now let the game continue
        //And let the player receive some attacks by the bots
        b1.attackPlayer(game.getPlayer1(), 8);
        b1.attackPlayer(game.getPlayer1(), 20);
        System.out.println("Player Health : " + game.getPlayer1().getHealth());


        //After 30 seconds, remove the power player settings
        //This is a possible implementation
        System.out.println("\nEnding Power Play Mode");
        game.setPlayer1(pp.getPlayer());
        System.out.println("Player Health : " + game.getPlayer1().getHealth());

        //Now let the game continue
        //And let the player receive some attacks by the bots
        b1.attackPlayer(game.getPlayer1(), 8);
        b1.attackPlayer(game.getPlayer1(), 20);

        System.out.println("Player Health : " + game.getPlayer1().getHealth());

        //Finally How you end the game is up to you!
    }

}



Signing Off
Ryan

Sunday, January 17, 2010

Apache Tomcat jar locking issue.

This is a log of an issue that I faced during my experiments with deploying web applications that had dependencies on jar files in Tomcat.

At the time of writing this post, I am using a Windows XP machine, and Apache Tomcat 6.0. The IDE that I use for development is Netbeans 6.1.

The problem that I was facing was that when I deploy a web application on Tomcat from the IDE or from the Tomcat manager console, certain jar files in the lib directory of my application get locked. This happened when I tried to deploy an application that referenced a hibernate jar files and struts 2 jar files.

I came to know that they were locked when I tried to use the "Clean and Build" feature of Netbeans. My system was unable to delete certain jar files, and hence a complete clean and build was not possible until I stopped my Tomcat server. Even manual deletion of the files was not possible without server restart.

Well, I know that I could have used the unlokcer tool for windows which is a freeware to unlock my jar files, but since this does not seem to be a trivial issue, I expected a better solution.

Then after searching the web for a while, I came to know that the problem mainly persists in windows machines that use Tomcat.

Fortunately, Tomcat 6 as a feature that enables you to provide information specific to your web application in the context.xml wherein you can explicitly specify that the jar files used by your web application are not locked by Tomcat.

So, here is a sample context.xml that can be used to resolve this issue.






The path attribute is mandatory. set it to the name of the root of your web application.

To make this work for you, follow these steps.

  • Undeploy your webapp.
  • Restart the server.
  • Add the antiJARLocking and antiResourceLocking attributes to your context.xml file as shown above.
  • Deploy your application.
No more locking problems. You can now use the clean and build feature of your ide without any more hassles.

I have no idea if there is a fix for the locking issue in previous versions of Tomcat or if this issue happens in all windows machines. But this simple configuration did the trick for me. And I hope it does works for you as well.


Signing Off
Ryan

struts 2 tags demo : select tag

In this post we are going to see examples of how to use the struts 2 select tag in our jsp pages.

NOTE : The examples in this post are just bare bones examples and do not necessarily demonstrate the way that you should design the flow of your code.

To begin with, I would like to list down the prerequisites for these examples that are set up on my system.

Struts version : struts-2.1.8.1

jar files to include in your lib directory :

  • commons-fileupload-1.2.1.jar
  • commons-logging-1.0.4.jar
  • freemarker-2.3.15.jar
  • ognl-2.7.3.jar
  • struts2-core-2.1.8.1.jar
  • xwork-core-2.1.6.jar

Although the code that is written here does not mandate the need of an IDE and can be written using a simple text editor, however, during my experiments, I have been using Netbeans 6.8.

Server : Tomcat 6.0

That takes care of the runtime environment.

Now about our examples.

In the code sample below, i am going to create something of the sort of an ice cream parlor that gives the user an option to select the flavor of his choice by using the struts 2 select tag. The user can submit his choice to an action that prints the user's choice on the server logs using the omnipresent System.out.println().

First, our Flavor class :


public class Flavor {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }
}





The Bean that handles the creation of a list of flavors that will be used in the select tag.

package sample;

import com.opensymphony.xwork2.ActionSupport;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author ryan
 */
public class IceCreamCorner extends ActionSupport{
    
    private List flavors;

    public List getFlavors() {
        return flavors;
    }

    @Override
    public String execute()
    {
        System.out.println("Inside IceCreamBean : Method : Execute.");
        /*
         * Please note that this way of initializing is just for demonstration purposes
         * In real applications, you will fetch this data using a DataAccessObject (DAO).
         * Or if you are using spring/hibernate/EJB, the Flavor class can be an entity.
         * The only objective in this example is to populate a list with Flavor objects.
         */
        Flavor f1=new Flavor();
        Flavor f2=new Flavor();
        Flavor f3=new Flavor();

        flavors=new ArrayList();

        f1.setName("Vanilla");
        f1.setId(1);

        f2.setName("Chocolate");
        f2.setId(2);

        f3.setName("Strawberry");
        f3.setId(3);

        flavors.add(f1);
        flavors.add(f2);
        flavors.add(f3);

        System.out.println("Flavor list size : "+flavors.size());
        return ActionSupport.SUCCESS;
    }
}




Following is the class that the user will submit his flavor choice for further processing.


package sample;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;

/**
 *
 * @author ryan
 */
public class FormAnalyzer extends ActionSupport{

    @Override
    public String execute()
    {
        System.out.println("Inside FormAnalyzer : Method : execute");
        ActionContext ac = ActionContext.getContext();

        HttpServletRequest request=(HttpServletRequest)ac.get(ServletActionContext.HTTP_REQUEST);

        Enumeration paramNames= request.getParameterNames();

        while(paramNames.hasMoreElements())
        {
            String param=(String)paramNames.nextElement();
            System.out.println("\nParameter Name : "+param);
            System.out.println("Parameter Values : ");
            
            String[] paramValues=request.getParameterValues(param);
            
            for(String paramVal:paramValues)
            {
                System.out.println(paramVal);
            }
            
        }

        return ActionSupport.ERROR;
    }
}


The struts.xml configuration file.



 

        
            
             
                /success.jsp
            
            
                /failure.jsp
                /success.jsp
            

        



First let me demonstrate using the struts 2 select tag with a dynamically created list



            
            
            
        

In this example, the value that is sent to the FormAnalyzer class is the value of the text that is displayed in the drop down menu.

Before we use the list of flavors of ice creams in the select tag, first the list needs to be initialized. In our example here, we will achieve that by calling an action in the page that will do nothing but populate our list. We will store this action object as a variable on our page and later access this action object to retrieve the list of flavors.

The action object that will be used here is an object of class IceCreamCorner. Thw following line will have to be included before executing any select tag for the examples given in this post.




Now, you can use the given examples and see for yourself the effects of setting the different tag attributes of the struts 2 select tag.

Example 1 : Demonstrating the use of the s:select tag with the listKey and listVaue attributes


            
            
            
        



Example 2 : Demonstrating the use of the s:select tag without the listKey attribute In this case, the String representation of the list object,i.e. toString() value, itself is sent as the paramter value which is not a very useful thing to do. Hence, it makes more sense to use the listValue attribute with the listKey attribute.



            
            
            
        


Example 3 : Demonstrating the use of the s:select tag with a predefined selected value


            
            
            
        



Example 4 : Demonstrating the use of the s:select tag which can have multiple selections



            
            
            
        


I Hope that helps.

Signing Off
Ryan

Sunday, January 10, 2010

Creating Custom Interceptors in Struts2

In this post, i am going demonstrate how to create your own custom interceptor in Struts 2.

In my previous post here I demonstrated how to declare and configure interceptors in the struts.xml file. In this post we will see how to create a simple interceptor that will execute and print a few lines to the server logs, both before and after an action is executed.

A few points need to be kept in mind before writing your own interceptors ;
  1. You can create your own custom interceptor in two ways
    Implement the Interceptor interface
    Extend the AbstractInterceptor class.

  2. If You are implementing the Interceptor interface, you have to provide implementations to three methods :
    void destroy();
    void init();String intercept(ActionInvocation invocation) throws Exception;

  3. The 'init' method is called before the 'intercept' method is called. An interceptor instance is created once and is reused over many requests. Hence the interceptor code must be written to be thread safe.

  4. The 'intercept' is the place where you write the business logic code of your interceptor.

  5. The 'destroy' method is executed on application shutdown and is used to release resources used by the interceptor that have been allocated in the init method.

  6. If you are extending the AbstractInterceptor class, you only need to override the method :
    String intercept(ActionInvocation invocation) throws Exception method to provide your own implementation.

  7. In our example we will be extending the AbstractInterceptor class.
I first begin by creating a dummy action.



package sample;

import com.opensymphony.xwork2.ActionSupport;

/**
 *
 * @author ryan
 */
public class DummyAction1 extends ActionSupport{

    public String execute()
    {
        System.out.println("Inside DummmyAction1");
        return ActionSupport.SUCCESS;
    }
}


Now i create two interceptor classes.


package interceptors;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 *
 * @author ryan
 */
public class MyInterceptor1 extends AbstractInterceptor{

    @Override
    public String intercept(ActionInvocation ai) throws Exception {
        System.out.println("Inside MyInterceptor1- Before Executing Action");
        //System.out.println("Next Invocation will invoke : "+ai.invoke());
        String invocationResult = ai.invoke();

        System.out.println("Inside MyInterceptor1- After Executing Action");
        return invocationResult;
    }

}



package interceptors;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 *
 * @author ryan
 */
public class MyInterceptor2 extends AbstractInterceptor{

    @Override
    public String intercept(ActionInvocation ai) throws Exception {
        System.out.println("Inside MyInterceptor2- Before Executing Action");
        
        String invocationResult = ai.invoke();

        System.out.println("Inside MyInterceptor2- After Executing Action");
        return invocationResult;
    }

}




The following code shows the configuration of struts.xml



 

        
            
                
                
            

            
                
                
                /success.jsp
            
        
        



You can test this code by adding the following two lines on your jsp page to invoke your action.



Click To Test Interceptors

Since the action is already configured such that the two interceptors will be called before and after it is executed, you can check your server logs to ensure that the interceptors are executing in the order as specified in the configuration.

My Tomcat logs show the following : 


Inside MyInterceptor1- Before Executing Action
Inside MyInterceptor2- Before Executing Action
Inside DummmyAction1
Inside MyInterceptor2- After Executing Action
Inside MyInterceptor1- After Executing Action


Now lets see what is happening in the code.

Consider the intercept method of MyInterceptor1. This method is called with an argument of type 'ActionInvocation'. The ActionInvocation object is created by the struts framework and is used as a handle to the execution environment of the interceptor. It contains several useful methods. You can find the list of methods in this extremely useful class at its documentation here.

The ActionInvocation object is the heart and soul of your interceptor class. As we have already seen earlier, we can have several interceptors for a given action. The information of the sequence in which these interceptors are executed for the action is stored in the ActionInvocation object. The next interceptor in the sequence is called by calling the invoke() method of the ActionInvocation object. For the first Interceptor, the invoke() method is called by the ActionProxy object.

Since the invoke method causes the next interceptor/action in the sequence to be executed, the interceptor is in absolute control of the execution and can decide at any moment whether to proceed with the next step in the sequence or to return an error to the caller without proceeding.

A point to be remembered is that String value returned by the the invoke() method is the value that is retrieved after the action and its result have been executed. In our example, when the myInterceptor1 interceptor calls its invoke, control is passed on to the myInterceptor2, which in turn calls the action. The action upon execution returns "success" as the string, which is in turn returned to the myInterceptor2, which is in turn returned to 'myInterceptor1'. At this point of time, the result has already been executed or your jsp page has already been rendered.

As done in the above example, you can save the return value in a local variable, perform some tasks. And if everything seems to be fine, you can simply return the value in the local variable at the end of the method.

So, we have finally created and configured a custom interceptor in a simple struts 2 application.

Signing Off
Ryan

Saturday, January 9, 2010

Struts 2 interceptors overview


Interceptors are are one of the most powerful features in struts 2. Interceptors are useful because they enable you to perform common tasks across actions withoug having the need to recompile the code. Interceptors are configured in the struts onfiguration file for an action.

Interceptors are executed in the sequence in which they are declared. A set of interceptors that are required to execute in a sequence can be grouped together to form an interceptor stack.

Interceptors are declared in the struts.xml file inside a package.
Following is an example of interceptor declaration in struts.xml





 
 


As already mentioned Interceptors are executed in a sequence. They can be grouped together and the grouping is given a name. For example :




 
 
 
 
  
  
 


The 'name' attribute of interceptor-ref element can take an interceptor name or an interceptor stack name as its value. For example,




 
 
 
 
 
  
  
 
 
 
  
  
 


So, now we are done with interceptor declaration. So, how do we use these interceptors for our action classes? Following is an example of using the above interceptors for an action class.




 .
 .
 interceptor declarations
 .
 .
 
 
  
  /success.jsp
 



In the above example, we have cofigured the 'iName1' interceptor to execute before the methods of the action class get executed. You can also configure an interceptor stack to execute for an action. Example :




 .
 .
 interceptor declarations
 .
 .
 
 
  
  
  /success.jsp
 


When a package extends another package, it inherits all the configuration of the parent package including interceptors and interceptor stacks. So by extending the struts-default package, we get access to several useful preconfigured interceptor stacks namely




  • defaultStack
  • completeStack
  • basicStack

and many other interceptor stacks, and also a number of interceptors namely



  • exception
  • servlet-config
  • prepare
  • static-params
  • params
  • conversion-error
  • validation
  • workflow
  • model-driven
  • chain
  • i18n
  • execAndWait


Sometimes you need to execute a given interceptor/interceptor stack for all the actions in a package, and it can become quite frustrating to configure the same interceptor for each action. This can be avoided by configuring the package to have a default interceptor for all its actions. For example, in our code sample, if we want the 'myInterceptorStack' interceptor stack to be the default interceptor stack of that package, then we need to simply add one more element to the package element. Example :




 .
 .
 interceptor declarations
 .
 .
 
 .
 .
 action declarations
 .
 .
 
 


Well, thats it. :>



Signing Off
Ryan

Struts 2 Namespaces

Here are a few things that I learnt about struts 2 namespaces during my silly experiments.


  1. The namespace attribute of element in struts.xml is an optional attribute. The default namespace is "" . i.e. an empty string.

  2. The value of your namespace must always begin with a "/".

  3. Namespaces are used to group together a set of actions.

  4. An action with the same name can exist in several namespaces. The action that will be invoked depends upon the namespace in which it is called.

According to the struts 2 documentation, struts 2 tags are meant to be namespace aware. i.e. you should not need to append the namespace name in the url's and links in on a jsp page when creating links. However, it does not seem to be working for me. So, i use the namespace attribute whenever necessary.

However, if an action with the same name exists in multiple namespaces then the action in the default namespace is called if no namespace is specified in the link.

An important point to note is that when you declare a package with a namespace, all the results that you configure for an action usuing the result tag are assumed to be relative to that namespace if they are not preceded by a /.

For example suppose you have the following configuration in struts.xml such that the same action name is present in two packages but the namespaces are different. Let us assume that the name of your web application root is 'struts2app'



            
                success.jsp
            
        
 
            
                failure.jsp
            
        


In your jsp page, you can access action1 in namespace1 by writing the following code




Click Me To Test Namespace


Struts will look for the page success.jsp in struts2app/namespace1/success.jsp

However, if your success.jsp is exists direcly under the root directory, the you need to specify the result configuration as follows.




/success.jsp




The leading "/" indicates that the page is located at the web application root.
          
In this case, struts will try to find the page success.jsp in struts2app/success.jsp

That takes care of the bare basics of using namsepaces in struts 2.

Signing Off
Ryan