How To Set Conditional Debug Breakpoints in Eclipse or IBM RAD?

Developers and Production Support Analysts will, in their lifetime, spend a lot of time debugging, specially if the applicaiton is complex and they have no idea on what’s going on. I mentioned Production Support Analysts because they are the ones in most companies analyzing and fixing the defects in production environments. Developing the new features probably does not need you as much to debug as it needs for maintenance work, specially if you are trying to understand what’s going on and what is the flow.

There are many occasions you don’t want to debug every steps. For example, if there is a for loop that loops for a 1000 times and that you know it fails on the 100th step or are intersted to see what’s going on somewhere around that, would it make sense to go through the 99 steps of debugging before hitting the 100th one? It certainly does not make sense to me unless you have a lot of time to hit those debug short cuts (I love those F5,F6,F7,F8 shortcut keys in Eclipse and IBM RAD by the way).

So what can you do about it? Well the IDEs like Eclipse or IBM RAD offer you a way to set conditional breakpoints – the IDE will stop at the breakpoint you set only when certain conditons are met.

The following is some piece of code with a for-loop. Let’s say we are interested to look at the value of the variable ‘random’ when the value of i is 100.

package com.kushal.tools.published;
/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * www.icodejava.com
 * 
 * Written to be used in a tutorial to show how to do 
 * conditional break points in eclipse
 */

public class ConditionalBreakPointEclipse {

    public static void main(String args[]) {

        doSomeStuff();
    }

    /** Just outputting some random numbers. We would like to
     * add a conditional breakpoint when the value of i is 100.
     */
    public static void doSomeStuff() {

        for (int i = 0; i <= 1000; i++) {

            double random = i * Math.random();

            System.out.println(i + " - Random - " + random);
        }
    }

}

The first step is to set a breakpoint where it says

double random = i * Math.random();

Here is a screenshot for that.

Eclipse - Putting a breakpoint

The second step is to right click on the breakpoint and choose ‘Breakpoint Properties…’.

Eclipse - right click on the breakpoint

On the third step, enable the checkbox ‘Conditional’. The text area underneath the checkbox will be enabled and that is a place where you can put your conditions. In my case, I simply typed in i==100 because I wanted to stop when the value of i is 100.

Eclipse - Adding the conditional in the Line Breakpoint Properties

Now close the window and run the application in debug mode. You will see that after the value of i reaches 100 and when the statement where we put the breakpoint is reached, the IDE will stop for you to evaluate the variables at that point. Isn’t that neat? Once you hit F7, the program should continue without another stop at the breakpoint.

Eclipse - Debugging with conditional breakpoint

Compare this to not having a conditional breakpoint. You would have to step through 99 times before it reached your desired value of i and to finish debugging the program, you would have to hit F7 for another 900 times (or just stop debugging)!!

You are going to appreciate that IDEs provide this great feature.

Java Tip: How to extract the content of a Jar File Using Command Prompt

To extract the files from a jar file, use x, as in:

jar xf myFile.jar

To extract only certain files from a jar file, supply their filenames:

jar xf myFile.jar foo bar

How to capture a screenshot using Java and save it to a file?

A screenshot, screen capture, or screen dump is an image taken by the computer to record the visible items displayed on the monitor or another visual output device. Usually this is a digital image taken by the host operating system or software running on the computer device, but it can also be a capture made by a camera or a device intercepting the video output of the computer.

Screenshots, screen dumps, or screen captures can be used to demonstrate a program, a particular problem a user might be having or generally when computer output needs to be shown to others or archived, or to simply show off what you do on your computer to others. [Wikipedia]

The following java program demonstrates how to use Robot class from java.awt package to capture screenshots and save the image thus captured to disk.

package com.kushal.utils;

/**
 * @author Kushal Paudyal
 * JavaScreenCaptureUtil.java
 * 
 * This utility captures the screenshot and saves
 * the captured image to disk.
 */
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.imageio.ImageIO;

public class JavaScreenCaptureUtil {

	public static void main(String args[]) throws Exception {

		/**
		 * This class (Robot.java) is used to generate native system input events for the 
		 * purposes of test automation, self-running demos, and other 
		 * applications where control of the mouse and keyboard is needed. 
		 * The primary purpose of Robot is to facilitate automated testing 
		 * of Java platform implementations. 
		 */
		Robot robot = new Robot();
		
		/**
		 * Get the current screen dimensions.
		 */
		Dimension d = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());
		int width = (int) d.getWidth();
		int height = (int) d.getHeight();
		
		
		/**
		 * Delay the robot for 5 seconds (5000 ms) allowing you to switch to proper
		 * screen/window whose screenshot is to be taken.
		 * 
		 * You can change the delay time as required.
		 */
		robot.delay(5000);
		
		/**
		 * Create a screen capture of the active window and then create a buffered image
		 * to be saved to disk.
		 */
		Image image = robot.createScreenCapture(new Rectangle(0, 0, width,
				height));

		BufferedImage bi = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		Graphics g = bi.createGraphics();
		g.drawImage(image, 0, 0, width, height, null);

		/**
		 * Filename where to save the file to.
		 * I am appending formatted timestamp to the filename.
		 */
		String fileNameToSaveTo = "C:/temp/screenCapture_"
				+ createTimeStampStr() + ".PNG";
		
		/**
		 * Write the captured image to a file.
		 * I am using PNG format. You can choose PNG, JPG, GIF.
		 */
		writeImage(bi, fileNameToSaveTo, "PNG");

		System.out.println("Screen Captured Successfully and Saved to:n"+fileNameToSaveTo);

	}

	/**
	 * This method writes a buffered image to a file
	 * 
	 * @param img -- > BufferedImage
	 * @param fileLocation --> e.g. "C:/testImage.jpg"
	 * @param extension --> e.g. "jpg","gif","png"
	 */
	public static void writeImage(BufferedImage img, String fileLocation,
			String extension) {
		try {
			BufferedImage bi = img;
			File outputfile = new File(fileLocation);
			ImageIO.write(bi, extension, outputfile);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @return String representation of timestamp 
	 * in the format of yyyyMMdd_hhmmss (e.g. 20100426_111612)
	 * @throws Exception
	 */
	public static String createTimeStampStr() throws Exception {
		Calendar mycalendar = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_hhmmss");
		String timeStamp = formatter.format(mycalendar.getTime());

		return timeStamp;

	}

       /*
	 * SANJAAL CORPS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE
	 * SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT
	 * LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
	 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SANJAAL CORPS SHALL NOT BE
	 * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
	 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
	 * 
	 * THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
	 * CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
	 * PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
	 * NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
	 * SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
	 * SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
	 * PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). SANJAAL CORPS
	 * SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
	 * HIGH RISK ACTIVITIES.
	 */

}