Generate XML – DBMS_XMLGEN

On my way to my solution store just found this nice to use, old and easy feature.
Possibilities endless, usage typically very easy.

I used the following to generate XML from sqlplus:

 select dbms_xmlgen.getxml('select * from user') from dual; 

Output:

< ROWSET >
 < ROW >
  < TNAME >Employee< / TNAME >
  < TABTYPE > TABLE < / TABTYPE >
 < / ROW >
< / ROWSET >

Command, Singleton, JMenuItem, JButton, AbstractButton – One Listener for the app

Here I would like to demonstrate a simple use of JMenuItems being used with Single Listener for the entire system.
A simple sample of use would probably be SingleInstance Desktop Application.

Lets see how that is done here.

1. First lets create a OneListener class that should be able to listen to ActionEvents and also be able to add Commands to itself. Please refer to my previous post on Command,Singleton if you would like to see more about this patterns and there usage.

  1. package com.shaafshah.jmenus;
  2.  
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. import java.util.ArrayList;
  6.  
  7. import javax.swing.AbstractButton;
  8.  
  9. // Implements the ActionListener and is a Singleton also.
  10.  
  11. public class OneListener implements ActionListener{
  12.  
  13. 	private static OneListener oneListener = null;
  14.  
  15. 	// Holds the list of all commands registered to this listener
  16. 	private ArrayList<Command> commandList = null;
  17.  
  18. 	// A private constructor
  19. 	private OneListener(){
  20. 		commandList = new ArrayList<Command>();
  21. 	}
  22.  
  23. 	// Ensuring one instance.
  24. 	public static OneListener getInstance(){
  25. 		if(oneListener != null)	
  26. 			return oneListener;
  27. 		else return oneListener = new OneListener();
  28. 	}
  29.  
  30. 	// Add the command and add myself as the listener
  31. 	public void addCommand(Command command){
  32. 			commandList.add(command);
  33. 		    ((AbstractButton)command).addActionListener(this);
  34. 	}
  35.  
  36.  
  37. 	// All Events hit here.
  38. 	@Override
  39. 	public void actionPerformed(ActionEvent e) {
  40. 		((Command)e.getSource()).execute();
  41. 	}
  42.  
  43. }

In the above code, the addCommand method adds the command Object and adds a listener to it.
Now how is that possible.
Basically because I am categorizing my UI objects as Commands with in the system having some UI. And I am also assuming that these commands are Currently AbstractButton i.e. JMenuItem, JButton. Lets have a look at the Command Interface and its Implementation.

  1. public interface Command {
  2. 	public void execute();	
  3. }

And the implementation, note that the Command is an interface where as the class is still extending a UI object.

  1. import javax.swing.JMenuItem;
  2.  
  3. public class TestCmd extends JMenuItem implements Command{
  4.  
  5. 	public TestCmd() {
  6. 		super("Test");
  7. 		OneListener.getInstance().addCommand(this);
  8. 	}
  9.  
  10. 	@Override
  11. 	public void execute() {
  12. 		System.out.println("HelloWorld");
  13. 	}
  14. }

Personally don’t like calling the OneListener in the constructor of the class but just for the sake of simplicity of this post I have left it that way. There are many different ways to omit it.

So the TestCmd is a JMenuItem but is also a Command and thats what the OneListener understands.
As this commads Listener is also OneListener all ActionEvents are thrown there and from there only the Command.execute is called on.

So now you dont have to worry about what listeners are you in. The only thing you know is that when execute is called you need to do your stuff.

You can download the code from Here.

Hope this helps.

Doing the Locale – Danmark

The following illustrates how to get the Number format working with a danish locale.

  1. import java.text.NumberFormat;
  2. import java.util.Currency;
  3. import java.util.Locale;
  4.  
  5.  
  6. public class TestLocale {
  7.  
  8.  public static void main(String args[]){
  9.  // Create a Locale for Danmark
  10.  Locale DANMARK = new Locale("da","DK");
  11.  
  12.  // get the currency instance for this locale.
  13.  Currency krone = Currency.getInstance(DANMARK);
  14.  
  15.  // Get a Number format for the locale.
  16.  NumberFormat krFormat = NumberFormat.getCurrencyInstance(DANMARK);
  17.  // A symbol for the currency
  18.  String symbol = krFormat.getCurrency().getSymbol();
  19.  // A double amount
  20.  double amount = 10000.25;
  21. // print it out after formatting.
  22.  System.out.println(krFormat.format(amount));
  23.  }
  24. }

How to read a file from the JAR?

Someone just asked me this question today. And I thought might as well put it down for info.

  1.  public TestReadFileFromJar() throws FileNotFoundException, IOException {
  2.         InputStream is = getClass().getResource("txtData/states.properties");
  3.         read(is);
  4. }

In the case above txtData is placed in the jar on the root. Remmember to add the path with the /

Command

By using the command pattern you are seperating the operation from the invoking object. And just because of that it becomes easier to change the command without chagning the caller/s.
This means that you could use Command pattern when you might have the following situation

You want to parameterize objects to perform an action
You want to specify, execute and queue requests at different times.

Just to quickly start you need a command object, An interface will keep it easy going in this case, thus providing you with the option of extending other classes e.g. Swing MenuItem or Button.
Below the execute Method is the one invoked to do something when this command is called or asked to do its stuff.
Where as the getCommandName is assumed as a unique name how ever I am sure we can always come up with a better implementation for uniqueness.

  1. public interface Command {
  2.  
  3.     public void execute();
  4.     public String getCommandName();
  5.  
  6. }

And example implementation of the Command should look as follows
A Command Name, and and execute Method to tell what happens when this command is called.

  1. public class ForwardCmd implements Command {
  2.  
  3.    private String COMMAND_NAME = "Back";
  4.  
  5.    public BackCmd() {
  6.        super();
  7.    }
  8.  
  9.    public String getCommandName() {
  10.        return COMMAND_NAME;
  11.     }
  12.  
  13.     public void execute() {
  14.         System.out.println("Your wish, my command");
  15.     }
  16. }

The command manager is the controller in this case. It registers command objects. the “registerCommand” will simply take a command and store it in a list or something alike. This means you could load it out of a jar file, or an xml or path and just pass the object to the “registerCommand” AS a command offcourse.

the “execute” Command will simply execute the Command passed to it.

And the “getCommand” returns a command by looking up a COMMAND_NAME. So if you provide a name to it through you system it should give you an object of type Command and simple pass it to execute. Again this would be a controller logic and not the client one.

  1. public abstract class AbstractCommandManager {
  2.  
  3.     public abstract void registerCommand(Command command);
  4.     public abstract Collection getAllCommands();
  5.     public abstract void execute(Command command);
  6.     public abstract Command getCommand(String name);
  7. }

Implementing the adapter

Typically when implementing an interface you would have to implement all the methods that exist in that interface. A very good example is the MouseListener in the java Swing. When you need to implement more then one method where as typically you might be catching only one of them. Saying that you would also find a Mouse Adapter provided as well. Some of us use that often. And that is part of the Adapter pattern. It makes life easier for me sometimes.

Adapter a structural pattern will let you adapt to a different environment. The joining between different environment is called Adapter. Thus basically giving others the interface that they expect or vice versa when your program becomes the client.

For example the following class expects that the implementing class should be implementing all three methods.

  1. public interface RecordListener {
  2.  
  3. public void eventPrePerformed(RecordEvent recordEvent);
  4.  
  5. public void eventPerformed(RecordEvent recordEvent);}
  6.  
  7. public void eventPostPerformed(RecordEvent recordEvent);
  8.  
  9. }

So lets say our implementing class is a rude one and only wants to implement one method. What do you do as an API designer. hmmm

Thats where we step in with the Adapter.

  1. public abstract class RecordAdapter implements RecordListener {
  2.  
  3. public void eventPrePerformed(RecordEvent recordEvent) {}
  4. public void eventPerformed(RecordEvent recordEvent) {}
  5. public void eventPostPerformed(RecordEvent recordEvent) {}
  6.  
  7. }
  8.  
  9. public MyAdapterImpl extends RecordAdapter{
  10.  
  11. public void eventPerformed(RecordEvent recordEvent){}
  12.  
  13. }

Now the only thing left to do is use the adapter. And override any method that you might need .

  1. public MyClientClass {
  2.  
  3. public MyClientClass(){
  4.  
  5. this.addRecordListener(new MyAdapterImpl());
  6.  
  7. }
  8.  
  9. }

Abstract Factory pattern

Factories have been a key pattern in building applications, its fascinatingly simple, effective and to the point. When starting to learn a design oriented approach to applications or API, I would always recommend a factory pattern as one of the key starting notes of highlight in your design.

So today I am talking about the Abstract Factory pattern. Its not an “abstract” class or object that you call a pattern. But its a Factory of facotries and that is what exactly makes it so much wordingly abstract. Having “abstract” classes is there but just some other side of the coin.

When should I use an Abstract Factory:

  • Independence of how products are created, composed or represented
  • Should be configurable with one of the multiple families or products
  • You need enforcable constraints for the products used as a group
  • You need to reveal only the interfaces of products and not thier implementation as part of a bigger picture.

So lets begin with the fun.

This is how I plan to implement it:
Has A:
Product has a Specification
Factory has a Product
FactoryManager has FactoryConstants
FactoryManager has ComputerFactory

Is A:
BFactory is a ComputerFactory
AFactory is a ComputerFactory

Not shown.
ProductA is a Product
ProductB is a Product

Diagram:

AbstractFactory
AbstractFactory

Creating a simple factory that returns products.

  1. public abstract class ComputerFactory {
  2.  
  3.  public abstract String getName();
  4.  
  5.  public abstract Product[] getProducts();
  6.  
  7.  public abstract Product getProduct(int ProductID);
  8.  
  9. }

Implementation of the ComputerFactory

  1. public class AFactory extends ComputerFactory {
  2.  
  3. public String getName(){
  4. return "A";
  5. }
  6.  
  7. public Product[] getProducts(){
  8. return null;
  9. }
  10.  
  11. public Product getProduct(int productID){
  12. switch(productID){
  13. case 1:
  14. return new ProductA();
  15.  
  16. case 2:
  17. return new ProductB();
  18.  
  19. default:
  20. throw new IllegalArgumentException("Sorry you hit the wrong factory, we closed down in 1600 BC");
  21. }
  22. }
  23. }

A register base for factories. Refer to the main method for use later in this post.

  1. public interface FactoryConstants {
  2.  
  3.  public int A = 1;
  4.  public int B = 2;
  5.  
  6. }

The main Entrant class. the Factory Manager that will give the ComputerFactory resultant. Its assumed to be a Singleton as it registers as a Creator in the system (assumption).

  1. public class FactoryManager{
  2.  
  3.  private static FactoryManager factoryManager = null;
  4.  
  5.  private FactoryManager(){
  6.  
  7.  }
  8.  
  9.  public static FactoryManager getInstance(){
  10.   if(factoryManager != null){
  11.    return factoryManager;
  12.   }
  13.   else return factoryManager = new FactoryManager();
  14.  }
  15.  
  16.  public ComputerFactory getFactory(int factory) throws IllegalArgumentException{
  17.  
  18.   switch(factory){
  19.    case FactoryConstants.A:
  20.    return new IBMFactory();
  21.  
  22.    case FactoryConstants.B:
  23.    return new SUNFactory();
  24.  
  25.    default:
  26.    throw new IllegalArgumentException("Sorry you hit the wrong factory, we closed down in 1600 BC");
  27.   } 
  28.  }
  29. }

A main method to test the AbstractFactory

  1.  public static void main(String args[]){
  2.  
  3.   System.out.println(FactoryManager.getInstance().getFactory(FactoryConstants.A).getName());
  4.   System.out.println(FactoryManager.getInstance().getFactory(FactoryConstants.B).getName());
  5.   System.out.println(FactoryManager.getInstance().getFactory(3).getName());
  6.  
  7.  }

You can find the complete code listing here:
AbstractFactory source

Quick start Singleton – Walk through

This being my first existence on the network and I just want to make sure that I would come back to this blog page again sometime and keep on writing. For now this is a quick 5 min walk through of getting your hands dirty on the Singleton Pattern. As any ones first pattern Singleton always seems to be the easiest to adapt and ironically always the mistress of your pains; when you realize the act wasn’t right in the first place.
More details on that later.

This post should help you to get your hands right on the Singleton Pattern and find the kind there off.

Like any other pattern Singleton also has an objective behind it. What is that?

Motivation:

A Singleton ensures that a class has only one instance, and provides a global point of access to that class.

Benefits
The very simple benefits of a singleton can be:

* Controlled access
* Permits a variable number of instances
* Reduced name space

When to use:
There must be exactly once instance of a class

How to use: Walk Through

1. Create a class

  1. public class SimplySingleton{}

2. Declare a member variable. This variable will be used for keeping the singleton instance.

It has to be private so that it is not accessible from anywhere else. It has to be static so that it holds only one instance in all entirety.

  1. private static SimplySingleton simplySingleton = null;

3. Declare a private constructor.

Creating a private constructor would mean no one else can instantiate this class.

  1. private SimplySingleton(){}

4. So now everything seems private how do we access it. Create a global access point.

  1. public static SimplySingleton getInstance(){}

How would I access it from outside SimplySingleton.getInstance();

This method should return a SimplySingleton instance.

So here comes the logic to create the one and only instance.

  1. // 4a. is the variable null?
  2. if(simplySingleton != null)
  3. return simplySingleton;
  4. // 4b. if not assign it an instance.
  5. else return simplySingleton = new SimplySingleton();

Following is the complete code listing for writing a Singleton.

  1. // Declaring the class
  2. public class SimplySingleton {
  3.  
  4. // 1. a private and a static member variable
  5.  
  6. private static SimplySingleton simplySingleton = null;
  7.  
  8. // 2. a private constructor
  9.  
  10. private SimplySingleton(){}
  11.  
  12. // 3. a global access point
  13.  
  14. public static SimplySingleton getInstance(){
  15. // 4a. is the variable null?
  16. if(simplySingleton != null)
  17. return simplySingleton;
  18. // 4b. if not assign it an instance.
  19. else return simplySingleton = new SimplySingleton();
  20. }
  21.  
  22. }

Following are some good resources for in depth peek into the Singleton Pattern.

More Resources:

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

http://radio.weblogs.com/0122027/stories/2003/10/20/implementingTheSingletonPatternInJava.html

http://www.oodesign.com/singleton-pattern.html

http://www.oaklib.org/docs/oak/singleton.html