Logging with log4J isDebugEnabled

Alot of times I have seen the questions popping up whether to use isDebugEnabled property or not. Arguably most of the times or rather always about performance. Some of the stuff that I feel important about using it follows.

The answer is simple. It is made to be used. However using it has to be with caution.

For instance
If I am using the following line in my code.

  1. log.debug("I am there");

Thats an example of a good practise

However I can really blow it out of proportions if I do the following.

  1. // Not good practise
  2. if (log.isDebugEnabled()){
  3.     log.debug("I am there"); 
  4. }

And why exactly is that so. This is because the method debug in the class Category i.e. extended by Logger in the log4j libraries explicitly checks the mode for the logging itself.

Extract from the class org.apache.log4j.Category is below

  1. public void debug(Object message) {
  2. if(repository.isDisabled(Level.DEBUG_INT))
  3. return;
  4. if(Level.DEBUG.isGreaterOrEqual(this.getEffectiveLevel())) {
  5. forcedLog(FQCN, Level.DEBUG, message, null);
  6. }
  7. }

Okay so thats the case where we say dont use it. What about the one where we actually do use the isDebugEnabled property.

For instance you have a large parameter going in the debug.

  1. // Bad Practise
  2.  log.debug("XML "+Tree.getXMLText());

In such a case it can clearly be said “No dont do it!” If Tree.getXMLText is going to pull out all the hair out of the app then there is no use. As it will be constructed first and if the debug level is not enabled that would be a performance cost.

  1. // Good Practise
  2. if (log.isDebugEnabled()){
  3.     log.debug("XML "+Tree.getXMLText());
  4. }

Thus in the example above it would be wiser to use log.isDebugEnabled() just to make sure the mileage or cost stays lesser.

Calling wsadmin scripts from ant

You can simply add the following to a target.
For the following wsadmin should be in your PATH env.

< exec dir="." executable="wsadmin.bat" logError="true" failonerror="true" output="wsconfig.out" >
< arg line="-lang jython -f ../../createQFactory.py"/ >
< /exec >

All output will be logged to wsconfig.out


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; 


 < ROW >
  < TNAME >Employee< / TNAME >
 < / 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;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. import java.util.ArrayList;
  7. import javax.swing.AbstractButton;
  9. // Implements the ActionListener and is a Singleton also.
  11. public class OneListener implements ActionListener{
  13. 	private static OneListener oneListener = null;
  15. 	// Holds the list of all commands registered to this listener
  16. 	private ArrayList<Command> commandList = null;
  18. 	// A private constructor
  19. 	private OneListener(){
  20. 		commandList = new ArrayList<Command>();
  21. 	}
  23. 	// Ensuring one instance.
  24. 	public static OneListener getInstance(){
  25. 		if(oneListener != null)	
  26. 			return oneListener;
  27. 		else return oneListener = new OneListener();
  28. 	}
  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. 	}
  37. 	// All Events hit here.
  38. 	@Override
  39. 	public void actionPerformed(ActionEvent e) {
  40. 		((Command)e.getSource()).execute();
  41. 	}
  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;
  3. public class TestCmd extends JMenuItem implements Command{
  5. 	public TestCmd() {
  6. 		super("Test");
  7. 		OneListener.getInstance().addCommand(this);
  8. 	}
  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;
  6. public class TestLocale {
  8.  public static void main(String args[]){
  9.  // Create a Locale for Danmark
  10.  Locale DANMARK = new Locale("da","DK");
  12.  // get the currency instance for this locale.
  13.  Currency krone = Currency.getInstance(DANMARK);
  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 /


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 {
  3.     public void execute();
  4.     public String getCommandName();
  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 {
  3.    private String COMMAND_NAME = "Back";
  5.    public BackCmd() {
  6.        super();
  7.    }
  9.    public String getCommandName() {
  10.        return COMMAND_NAME;
  11.     }
  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 {
  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 {
  3. public void eventPrePerformed(RecordEvent recordEvent);
  5. public void eventPerformed(RecordEvent recordEvent);}
  7. public void eventPostPerformed(RecordEvent recordEvent);
  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 {
  3. public void eventPrePerformed(RecordEvent recordEvent) {}
  4. public void eventPerformed(RecordEvent recordEvent) {}
  5. public void eventPostPerformed(RecordEvent recordEvent) {}
  7. }
  9. public MyAdapterImpl extends RecordAdapter{
  11. public void eventPerformed(RecordEvent recordEvent){}
  13. }

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

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

wasprofile -create -delete

Sometimes you require to do things silently, without any questions asked and “Just Do It” attitude is required.

I often find my self with this problem.

If you want to delete or create a Websphere profile from your command line try the following. (I have tried on RSA only)

# deleteing a profile
wasprofile -delete -profileName MyProfile

You should get the following message on deletion

INSTCONFSUCCESS: Success: The profile no longer exists.

Creating a websphere profile

wasprofile -create -profileName MyProfile -profilePath \
[PROFILE PATH] -templatePath \
[RSA HOME]runtimes\base_v6\profileTemplates\default \
-nodeName [NODE NAME] -cellName [CELL NAME] -hostName [HOSTNAME].