Saturday, October 3, 2009

Debugging effectively in Eclipse

Eclipse can be used to debug your java applications. Here are a few tips that can help you debug better:

1. Remote Debugging The eclipse IDE can remote debug your web application. Imagine being able to debug your development server from your local machine. Eclipse can help you do this. First you need to instruct your application / server to listen on a port for debug messages. That can be done using the -Xdebug flag -

java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=8787,suspend=n

This tells the JVM to listen for specific debug messages on port 8787.

In eclipse open Bug Icon -> Debug configurations and select “Remote java application”. Mention the port and server address and you should now be able to remote debug the application. Make sure that the classes and source sync with each other. On a network where the bandwidth is poor, this technique will not work.

2. Use the display view: The debug perspective in eclipse can open up a “Display” view that allows you to dynamically enter some code for execution when you hit a breakpoint. This view is priceless. You can dynamically execute code related to the variables that are in scope. Use the icons available on the top right hand corner of the view to do this.

3. Set breakpoints at different levels: You can set class level, method level or line level breakpoints. Nothing special but once again it can save you time. Just set a breakpoint corresponding to a class declaration a method declaration or a specific line.

Set conditional breakpoints: Breakpoints can be triggered conditionally. Simple right click on a breakpoint and select “Breakpoint properties”

There are 3 settings that you can tweak.

  1. Hit count – Break only when code flow passes over this breakpoint N times.
  2. Condition – Break when a specific programmatic condition is reached.
  3. Suspend VM Vs Suspend Thread – This is useful when debugging multithreaded application. If you want to suspend only the current thread and not all threads that are running through this code flow, you can use this drop down.

4. Specify a detail formatter of your own: Use the Variables view to mention a detailed formatter for an object type. This will display the object in question in a different format when you look it up under Variables or in an inspection window.

5. Use inspection windows: Inspection windows can reveal the detailed object graph of the instance in question. Simply highlight the variable and type the shortcut ctrl+shift+i

6. Use all instances / references: Use the all instances / all references option in the Variables view to determine the usage of a particular Object type at runtime. Arguably a profiler might be better suited for this sort of work, but hey, you never know when you might need it.

7. Change variable values dynamically: You can use the Variables view to change the value of a variable dynamically. This helps to determine code flow control if you have conditional statements. You could also do the same using the Display view but the GUI helps.

8. Use the drop to frame feature: The “drop to frame” feature allows you to retrace your path after making a minor code change. The code flow goes back to the line of code you have dropped to and executes once again. You could even, say, change a database variable and drop back a few call stacks behind to retrace your steps.

That’s about the list of debugging tips I know. Do you have one that could help other developers ? Drop a comment.

Hibernate issue - hbm2java ignores nested-composite-element tag in mapping

A few days back I tried to use hbm2java tool for auto-generation of POJO. But it seems there is a bug in hibernate framework.

I wanted to add a new table with minimal repercussions in an existing application. I had employee table (primary key – empId), which had its own hbm file and POJO (auto-generated using hbm2java). I created a new table called employee_locale (primary key – empId, localeId) and moved few fields from employee to employee_locale table.

I did not want to change POJO as it was being used by several other components within the application. So I identified how to have single hbm for 2 tables in db, so that your POJO does not change. Assuming that a single POJO will be created, in which employee POJO will be having handler to employee_locale. And as a result I just need to delegate my original getter to the getter of employee locale using handler of employee_locale.

Updated hbm file -




When I tried to generate POJO using bm2java I was getting following error whilst building it -

[hibernatetool] Executing Hibernate Tool with a Standard Configuration [hibernatetool] 1. task: hbm2java (Generates a set of .java files) [hibernatetool] java.lang.ClassCastException: org.hibernate.mapping.Component cannot be cast to org.hibernate.mapping.OneToMany [hibernatetool] at org.hibernate.tool.hbm2x.Cfg2JavaTool.getRawTypeName(

After much of goggling I came to know it’s a known bug in Hibernate 3.1 -

Hibernate 3.1 Release Notes

Hibernate 3.1 Jira Issue

Thursday, August 27, 2009

Optimize Eclipse in 5 Steps

As one of the most popular IDEs for developing Java applications, Eclipse can be adjusted with plenty of preferences. Here are my five favorite adjustments to tweak the Eclipse IDE. It works well with either the newest Eclipse Galileo or one of the older releases like Ganymede or Europa.

1.Improve performance by modifying startup arguments Per default Eclipse starts with a low size of memory. This results in numerous garbage collections which slows the IDE. You can easily adjust the heapsize memory by setting vm parameters on startup. Use the -Xms parameter to set the minimum and -Xmx to set the maximum heapsize. I prefer to use 1 GB for both so the VM doesn't have to increase maximum heapsize during runtime.

On Windows systems put a shortcut to the eclipse.exe and edit the target with your prefered VM-settings:

path/eclipse/eclipse.exe -vmargs -Xms1000M -Xmx1000M

To track the currently used heap memory and manually trigger the garbage collector to free up memory, go to Preferences -> General and activate Show heap status.

2.Improve performance by deactivating unused plug-ins Each distribution of Eclipse contains plenty of plug-ins. It's possible to deactivate several unused plug-ins without uninstalling them. So feel free to re-activate them later on demand. Go to Preferences -> General -> Startup and Shutdown to configure which plug-ins will be activated on startup.

3.Automatically Organize Imports on save Eclipse is capable of adding imports to your classes automatically which is surely one of the most used features. The command can easily be accessed by using the appropriate keyboard shortcut. I recommend to let Eclipse automatically organize imports on save. Go to Preferences -> Java -> Editor -> Save Actions and activate Organize Imports. Feel free to add additional save actions here.

4.Refresh workspace automatically Per default Eclipse does not refresh the workspace automatically when some files in the workspace are modified from outside the IDE. So if you copy some resources into your workspace (e.g. some icons to be included into your UI) you have to explicitly press F5 on the changed project to trigger a refresh. It's possible to let Eclipse refresh the workspace automatically, go to Preferences -> General -> Workspace then check Refresh automatically. Some people claim that this feature might impact performance, but I've not seen any issues so far even on large workspaces. Let me know about your impressions.

5.Improve Package Explorer by using Java Type Indicator Per default the Package Explorer uses the same icon for each class file. It's possible to display different icons against the concrete file type, e.g. concrete class, abstract class, interface or enum. This can be activated in Preferences -> General -> Appearance -> Label Decorations. Just activate the checkbox Java Type Indicator.

I'm sure there're plenty more useful Eclipse adjustments. I would appreciate if you share your favorite tweaks with me. :)

Saturday, June 13, 2009

25 Things Everybody Should be Doing

1. Take a 10-30 minute walk every day, and while you walk, smile. It is the ultimate anti-depressant.

2. Sit in silence for at least 10 minutes each day. Talk to God (or to your higher power or meditate) about what is going on in your life. Buy a lock if you have to.

3. When you wake up in the morning complete the following statement, ’ My purpose is to__________ today. I am thankful for______________ ’

4. Eat more foods that grow on trees and plants.

5. Drink green tea and plenty of water.

6. Try to make at least three people smile each day.

7. Don’t waste your precious energy on gossip, energy vampires, issues of the past, negative thoughts or things you cannot control Instead invest your energy in the positive present moment.

8. Eat breakfast like a king, lunch like a prince and dinner like a begger.

9. Life is not fair, but it is still good.

10. Life is too short to waste time hating anyone.

11. Don’t take yourself so seriously. No one else does.

12. You are not so important that you have to win every argument. Agree to disagree.

13. Make peace with your past so it will not spoil the present.

14. Don’t compare your life to others. You have no idea what their journey is all about.

15. No one is in charge of your happiness except you.

16. Frame every so-called disaster with these words:’ In five years, will this matter?

17. Forgive everyone for everything.

18. What other people think of you is none of your business.

19. GOD (depending on your beliefs) heals everything - but you have to ask Him (translate to your religion).

20. However good or bad a situation is, it will change.

21. Your job will not take care of you when you are sick. Your friends will. Stay in touch!!!

22. Envy is a waste of time. You already have all you need.

23. Each night, before you go to bed complete the following statements: I am thankful for__________. Today I accomplished_________.

24. Remember that you are too blessed to be stressed.

25. When you are feeling down, start listing your many blessings. You will be smiling before you know it.

MySQL Server Installation Problems with Vista

Oh Vista, how do I dislike thee!

Grr - trying to install MySQl server 5.0 on Windows Vista 64 bit was rather frustrating, as it simply stopped with “Unable to start service, error 1067″. Especially annoying as I flawlessly installed the thing on my XP desktop in two minutes last night.

You would think someone would have fixed this now, but no, the googlesphere advice seemed to be to re-run the install program as administrator. This failed to work. But I gathered from faint intimations that you had to remove the service for it to be properly re-installed.

So, the steps that seemed to work for me were:

  1. Run regedit
  2. Delete the key MySQL from KEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
  3. Reboot (important, otherwise the service does not go away)
  4. Go to C:\Program Files\MySQL\MySQL Server 5.0\bin
  5. Right click on MySQLInstanceConfig.exe, and choose “Run as administrator”
  6. Set it up as you want, and cross your fingers when it comes to starting the service.
Worked for me!

Thursday, April 30, 2009

The Liskov Substitution Principle (LSP)

Continuing with Object Oriented Design Principles (i.e. Open/Close Principle), I would like to share Robert Martin's (Uncle Bob) view on Liskov Substitution Priciple (LSP) “Subtypes must be substitutable for their base types”

“If S is a subtype of T, objects of type S should behave as objects of type T, if they are treated as objects of type T”

The LSP seems obvious given all we know about polymorphism. Lets understand with an example –

Consider the following Rectangle class:

// A very nice Rectangle class.
public class Rectangle {
private double width;
private double height;
public Rectangle(double w, double h) {
width = w;
height = h;
public double getWidth() {return width;}
public double getHeight() {return height;}
public void setWidth(double w) {width = w;}
public void setHeight(double h) {height = h;}
public double area() {return (width * height);

Now, how about a Square class? Clearly, a square is a rectangle, so the Square class should be derived from the Rectangle class, right? Let’s see!


• A square does not need both a width and a height as attributes, but it will inherit them from Rectangle anyway. So, each Square object wastes a little memory, but this is not a major concern.

• The inherited setWidth() and setHeight() methods are not really appropriate for a Square, since the width and height of a square are identical. So we’ll need to override setWidth() and setHeight(). Having to override these simple methods is a clue that this might not be an appropriate use of Inheritance!

Here’s the Square class:

// A Square class.
public class Square extends Rectangle {
public Square(double s) {super(s, s);}
public void setWidth(double w) {
public void setHeight(double h) {

Everything looks good so far. But check this out!

public class TestRectangle {
// Define a method that takes a Rectangle reference.
public static void testLSP(Rectangle r) {
System.out.println(”Width is 4.0 and Height is 5.0? + “, so Area is ” + r.area());
if (r.area() == 20.0)
System.out.println(”Looking good!\n”);
System.out.println(”Huh?? What kind of rectangle is this??\n”);

public static void main(String args[]) {
//Create a Rectangle and a Square
Rectangle r = new Rectangle(1.0, 1.0);
Square s = new Square(1.0);
// Now call the method above. According to the
// LSP, it should work for either Rectangles or
// Squares. Does it??

Test program output:

Width is 4.0 and Height is 5.0, so Area is 20.0 Looking good!

Width is 4.0 and Height is 5.0, so Area is 25.0 Huh?? What kind of rectangle is this??

it looks like we violated the LSP!

• What’s the problem here? The programmer of the testLSP() method made the reasonable assumption that changing the width of a Rectangle leaves its height unchanged.

• Passing a Square object to such a method results in problems, exposing a violation of the LSP

• The Square and Rectangle classes look self consistent and valid. Yet a programmer, making reasonable assumptions about the base class, can write a method that causes the design model to break down

• Solutions can not be viewed in isolation; they must also be viewed in terms of reasonable assumptions that might be made by users of the design

• A mathematical square might be a rectangle, but a Square object is not a Rectangle object, because the behavior of a Square object is not consistent with the behavior of a Rectangle object!

• Behaviorally, a Square is not a Rectangle! A Square object is not polymorphic with a Rectangle object.

• The Liskov Substitution Principle (LSP) makes it clear that the ISA relationship is all about behavior

• In order for the LSP to hold (and with it the Open-Closed Principle) all subclasses must conform to the behavior that clients expect of the base classes they use

• A subtype must have no more constraints than its base type, since the subtype must be usable anywhere the base type is usable

• If the subtype has more constraints than the base type, there would be uses that would be valid for the base type, but that would violate one of the extra constraints of the subtype and thus violate the LSP!

• The guarantee of the LSP is that a subclass can always be used wherever its base class is used!

Thursday, April 23, 2009

How to Become Unforgettable

Yet another piece of blog from Robin Sharma which would help in shaping your career and taking it to new heights - A piece of being a Leader Without a Title involves being so brilliant, gifted and human at what you do that people cannot forget who you are. Your good name becomes tattooed on the minds and hearts of everyone whose lives you touch. Hoards of roving ambassadors tell everyone they know about the experience you created for them - and of your rare air genius. That's the space you need to play at. To succeed in business today. 4 Best Practices I teach to my clients that will help you get there: 1. Keep Your Promises. Trust lives at the foundation of every great relationship. And business is all about relationships. When people like you, they buy from you - and help you in all ways. By becoming impeccable with your word, trust grows wildly. 2. Be BIW (Best in World). Being excellent at what you do is just the price of admission in our globalized, uber-connected world. To succeed and be truly unforgettable, may I suggest that the standard you play at is The Best in The World. At my leadership seminars I sometimes run an exercise that begins with this question: "what 10 things would the person who is best in the world at what you do be doing on a regular basis that you are not doing?". Start your list. 3. Be Radically Ethical. The pristine reputation that took you decades to build could be torn down in 60 seconds of bad judgment. Seriously. Just watch the news these days and you'll get what I mean. To show leadership in business (and life) today, it's mission-critical to be radically ethical. No dishonorable move goes unnoticed. Decency wins. 4. Be fun. Whatever happened to fun? Stop taking life so seriously. Generate the ability to laugh - even at the toughest of times. You become unforgettable - and irresistible the moment you lighten up. And get that smile back on your face. Life's a short ride when you really think about it. Might be smart to enjoy every turn of it.