TweetFollow Us on Twitter

Feb 02 Java

Volume Number: 18 (2002)
Issue Number: 02
Column Tag: Java Workshop

Java Debugging Aids

by Andrew S. Downs

Stack traces, logging, and string searching

Introduction

Many developers begin their debugging efforts very informally with a set of print statements that dump information to the console. That approach eventually leads to diminishing returns, and it becomes time to move into the realm of the interactive debugger. Or is it?

Sometimes the simplest tools are the best. Interactive debuggers are wonderful, but they invariably require a developer to spend substantial time in several areas: learning how to use the product and then applying that knowledge during a debugging session.

Arguably the most useful things that interactive debuggers provide are stack traces and variable and register values. If you know where the program is currently executing and the current program state, you can often figure out how to proceed in locating the source of a bug.

Somewhere in-between the println calls and setting of conditional breakpoints ad nauseum lies a middle ground. Determining how the program reached a certain point during execution can be done with a stack trace, which is very easy to generate from a Java exception. Since exceptions can be generated (thrown) and immediately caught, they do not need to cause the program to stop running. Being able to send that information, along with program state data, to a file or to the console allows you to run the app for awhile and follow the execution, then evaluate the data later when determining how to find and fix a bug.

This article discusses several Java utility classes that may prove useful in your debugging efforts. The first class is a simple stack trace generator that can write its output to a file or the screen. The second two are file writer classes. The fourth class contains example methods that make string searches easier.

By themselves these classes will not find bugs, but they provide information to use as a starting point in determining what to try next or where to look when problems arise. They are invasive in that you need to insert calls into your code (which can be conditionally wrapped), but they provide more details than the typical print statement, so hopefully you will find the reward worth the extra effort.

StackTrace

The first listing contains the StackTrace class. There are three types of methods here: constructors, file writers, and toString() overloads. The class works by taking an existing or new exception object, and printing out the stack trace. This has the effect of generating a stack trace at any location in your program, which is very useful for following the flow of execution. Sending the output to a file is often the most useful, and if you can easily locate certain entries in the file you will be much happier. Several of the methods in this class accept a label to accompany the trace information.

Listing 1: StackTrace.java

StackTrace
Generate a stack trace. Optionally send the text representation back to the caller, write it to a file, 
and/or include a label and timestamp.

public class StackTrace {
	// Use the native system delimiter instead of hardcoded newlines.
	private static String lineSep = 
		System.getProperty("line.separator");

	// The default output file, which can be overridden by using one of the constructors.
	private static String filename = "StackTraceLog.txt";

	// The source of the stack trace.
	Exception exceptionObject;
	
	// In the empty constructor throw and catch the exception.
	//   It keeps the caller's code fairly clean.
	StackTrace() {
		try {
			throw new Exception();
		}
		catch (Exception e) {
			exceptionObject = e;
			write(filename, this.exceptionObject);
		}
	}
	
	// This constructor allows the caller to specify the output filename. It also generates an
	//   exception for the caller.
	StackTrace(String filepath) {
		try {
			throw new Exception();
		}
		catch (Exception e) {
			exceptionObject = e;
			write(filepath, this.exceptionObject);
		}
	}
	
	// This constructor allows the caller to specify the output filename and a previously 
	//   created exception.
	StackTrace(String filepath, Exception e) {
		write(filepath, e);
	}
	
	// This constructor takes an additional string that is printed before the stack trace. 
	//   Use it to put a label on a particular trace in the file.
	StackTrace(String filepath, Exception e, String s) {
		write(filepath, e, s);
	}
	
	// This constructor trims the trace to a specified number of lines before writing.
	StackTrace(int i) {
		try {
			throw new Exception();
		}
		catch (Exception e) {
			exceptionObject = e;
			write(filename, toString(e, i));
		}
	}

	// Write to file.
	public void write(String filepath, Exception e) {
		write(filepath, e, null);
	}
	
	// Write to file: timestamp the entry and include an optional string.
	public void write(String filepath, Exception e, 
										String s) {
		try {
			java.io.FileWriter f = 
				new java.io.FileWriter(filepath, true);

			f.write((new java.util.Date()).toString() + lineSep);
			
			if ((s != null) && (s.length() > 0))
			  f.write(s + lineSep);
			
			e.printStackTrace(new java.io.PrintWriter(f, true));

			f.write(lineSep);
			f.flush();
			f.close();
		}
		catch (java.io.IOException ee) {
		}
		finally {
		}
	}
	
	// Write to file, including a timestamp.
	public void write(String filepath, String s) {
		try {
			java.io.FileWriter f = 
				new java.io.FileWriter(filepath, true);

			f.write((new java.util.Date()).toString() + lineSep);
			
			if ((s != null) && (s.length() > 0))
				f.write(s + lineSep);
			
			f.flush();
			f.close();
		}
		catch (java.io.IOException ee) {
		}
		finally {
		}
	}
	
	// The requisite override. This allows easy onscreen display by the caller.
	public String toString() {
		String retval = 
			"<StackTrace Exception attribute is null>";
		
		if (this.exceptionObject != null)
			retval = toString(this.exceptionObject);
		
		return retval;
	}
	
	// A static toString() overload for convenience. This gives the caller "one-stop 
	//   shopping", but they have to generate the exception themselves.
	public static String toString(Exception e) {
		java.io.ByteArrayOutputStream b = 
			new java.io.ByteArrayOutputStream(1024);

		e.printStackTrace(new java.io.PrintWriter(b, true));
		return b.toString();
	}
	
	// A static toString() overload that limits the number of lines returned.
	public static String toString(Exception e, int numLines) 
	{
		java.io.ByteArrayOutputStream b = 
			new java.io.ByteArrayOutputStream(1024);

		e.printStackTrace(new java.io.PrintWriter(b, true));
		String s = b.toString();
		
		StringBuffer sb = new StringBuffer(s.length());

		java.util.StringTokenizer st = 
			new java.util.StringTokenizer(s, lineSep, false);
		
		int count = 0;
		
		while (st.hasMoreElements()) {
			sb.append(st.nextElement());
			sb.append(lineSep);
			
			count++;
			if (count >= numLines)
				break;
		}
		
		return sb.toString();
	}
}

LogFile

This class uses random access files rather than streams. The first method writes a string to a file, and the second returns the contents of a newline-delimited file to the caller.

Listing 2: LogFile.java

LogFile
Write a string to a file, delete a file, and return the contents of a file.

import java.io.*;
import java.util.*;

public class LogFile {
	protected static final String mFilename = "log.txt";
	protected static final boolean mUseTimestamp = true;
	
	public static void log(String msg) {
		try {
			RandomAccessFile raf = 
				new RandomAccessFile(mFilename, "rw");
		
			raf.seek(raf.length());
		
			if (mUseTimestamp) {
				Date d = new Date();
				raf.writeBytes(d.toString() + ":" + 
					System.getProperty("line.separator"));
			}
		
			raf.writeBytes(msg + 
				System.getProperty("line.separator"));
		
			raf.close();
		}
		catch (IOException e) {
			// File error? Write to the console instead.
			System.out.println(msg + 
				System.getProperty("line.separator"));
		}
	}
	
	public static String contents() {
		String retval = "";
		
		try {
			RandomAccessFile raf = 
				new RandomAccessFile(mFilename, "rw");
		
			long length = raf.length();
			
			raf.seek(0);
		
			long i = 0;
			String s = "";
			StringBuffer sb = new StringBuffer();
			
			if (sb != null) {
				while (i < length) {
					s = raf.readLine();
					
					if (s != null) {
						i += s.length();
						sb.append(s);
					}
					else
						break;
				}
		
				retval = sb.toString();
			}
			
			raf.close();
		}
		catch (IOException e) {
			System.out.println("IOException reading logfile" + 
				System.getProperty("line.separator"));
		}
		catch (NullPointerException e) {
			System.out.println("NullPointerException reading" +  
				" logfile" + System.getProperty("line.separator"));
		}
		
		return retval;
	}
}

FileUtils

This listing contains two methods: the first writes a string to a file, the second writes a stream of bytes. There is nothing fancy here: these convenience methods simply wrap the sometimes cumbersome sequence of calls that setup, write, and close files. Note that both of these methods first delete the file if it exists. This is less useful for a logfile, where you want to retain history, but if you are replacing an existing data file with a downloaded version, then it makes sense to first remove the original file.

Listing 3: FileUtils.java

FileUtils
Write a string or byte stream to a file. The byte stream is useful when dealing with binary (non-text) 
data.

import java.io.*;

public class FileUtils {
	public static void writeFile(String s, String path,
										String file) {
		try {
			File f = new File(path + file);

			// Deleting the file is appropriate if we are replacing old data with new data.
			if (f.exists()) {
				f.delete();
				f = new File(path + file);
			}
			
			FileOutputStream fos = new FileOutputStream(f);
			OutputStreamWriter w = new OutputStreamWriter(fos);

			w.write(s, 0, s.length());
			w.close();
			fos.close();
		}
		catch (IOException e) {
			System.out.println("IOException writing string.");
		}
	}

	public static void writeFileBytes(byte s[], int start, 
										String path, String file) {
		try {
			File f = new File(path + file);
		
			if (f.exists()) {
				f.delete();
			f = new File(path + file);
			}
			
			FileOutputStream fos = new FileOutputStream(f);

			// Buffered streams often provide better performance than their non-buffered 
			//   counterparts.
			BufferedOutputStream w = 
				new BufferedOutputStream(fos);

			// The start value is useful when writing the file in pieces (e.g. lots of data). 
			w.write(s, start, s.length - start);
			w.close();
			fos.close();
		}
		catch (IOException e) {
			System.out.println("IOException writing bytes.");
		}
	}
}

Stringutils

The ability to locate substrings is one of the best things about the java.lang.String class. The problem is that often you want to do more than simply locate a string: you may want to trim portions of it at the same time. The methods presented here wrap the standard search and replace functionality. The first method locates and returns a substring. The second locates and returns multiple occurrences of the search string. The third method is similar to the second, but it trims starting at the location of a substring within the found string (such as finding attributes within an HTML tag). The last method replaces a substring.

Each of these methods receives arguments that allow you to specify whether to locate and include a second string in the returned result. For example, if you are parsing HTML tags this allows you to remove the final ‘>' from the returned string. In many situations a simpler set of methods (with fewer options) will suffice.

Listing 4: StringUtils.java

StringUtils
Various string search and replace methods.

import java.util.*;

public class StringUtils {
	public static String findSubstring(String buffer, 
		String open, String close, boolean includeFront, 
		boolean includeBack) {
		String ref = null;

		int start = buffer.indexOf(open, 0);
		int end = buffer.indexOf(close, start);

		if (start >= 0 && end >= 0 && end > start) {
			// This complicated set of conditionals checks each combination for removing 
			//   the open and close strings from the result.
			if (!includeFront) {
				if (!includeBack)
					ref = buffer.substring(start + 
						open.length(), end);
				else
					ref = buffer.substring(start + 
						open.length(), end + close.length());
			}
			else {
				if (!includeBack)
					ref = buffer.substring(start, end);
				else
					ref = buffer.substring(start, end + 
						close.length());
			}
		}

		return ref;
	}

	public static Vector findStringOccurrences(String buffer, 
		String open, String close, boolean includeOpen, 
		boolean includeClose) {
		Vector v = new Vector();

		int fromIndex = 0;
		boolean found = true;

		String ref;

		// This is similar to the one-shot findSubstring() method above. 
		//   Note the added loop that ensures we catch all occurrences of the substring 
		//   in the entire string.
		while (found && fromIndex < buffer.length()) {
			int start = buffer.indexOf(open, fromIndex);
			int end = buffer.indexOf(close, start + 
				open.length());

			if (start >= 0 && end >= 0 && end > start) {
				<snip>
				// The if-else block from findSubstring() above goes here. 
				//   The logic is the same.

				// The vector will contain the occurrences of the substring.
				v.addElement(ref.toString());

				// Update the search starting point.
				fromIndex = start + 1;
			}
			else
				found = false;
		}

		return v;
	}

	public static Vector findStringOccurrences(String buffer, 
		String open, String offsetString, String close, 
		boolean includeFront) {
		Vector v = new Vector();

		int fromIndex = 0;
		boolean found = true;

		String ref;
		
		open = open.toUpperCase();
		offsetString = offsetString.toUpperCase();
		close = close.toUpperCase();
		
		String searchString = new String(buffer);
		searchString = searchString.toUpperCase();

		while (found && fromIndex < buffer.length()) {
			int start = searchString.indexOf(open, fromIndex);
			int end = searchString.length();
			
			// Locate a substring (offsetString) within the found string.
			// Note that this adjusts the start value for the substring operation.
			start = searchString.indexOf(offsetString, 
				start + open.length());
			
			if (close.length() > 0)
				end = searchString.indexOf(close, 
					start + offsetString.length());

			if (start >= 0 && end >= 0 && end > start) {
				// The logic is simpler in this method since we do not look for a 
				//   closing string.
				if (!includeFront)
					ref = buffer.substring(start + 
						offsetString.length(), end);
				else
					ref = buffer.substring(start, end);

				v.addElement(ref);

|				fromIndex = start + 1;
			}
			else
				found = false;
		}

		return v;
	}

	public static String replaceStringOccurrence(
		String buffer, String replacement, String open, 
		String close, int occurrence, boolean includeFront) {
		StringBuffer sb = new StringBuffer();

		int fromIndex = 0;
		boolean found = true;

		// Walk through the entire buffer, looking for the i-th occurrence of the 
		//   string (the variable named open).
		while (found) {
			int start = buffer.indexOf(open, fromIndex);
			int end = buffer.indexOf(close, start + 
				open.length());

			if (start >= 0 && end >= 0 && end > start) {
				fromIndex = start + 1;

				occurrence—;
				
				// Once the count reaches zero, we have located
				//   the starting point for the replacement operation.
				if (occurrence > 0)
					continue;

				// Assemble the string from front to back.
				//   This call can also be used to simply insert the replacement string by 
				//   setting includeFront to true. 
				if (includeFront)
					sb.append(buffer.substring(0, start + 
						open.length()));
				else
					sb.append(buffer.substring(0, start));

				sb.append(replacement);
				sb.append(buffer.substring(end));
				
				break;
			}
			else
				found = false;
		}

		return sb.toString();
	}

Conclusion

The classes and methods presented here should make your logging and debugging efforts a little easier for those times when you do not require an intimate session with the debugger. The methods can be used to help determine starting points for more detailed debugging efforts.


Andrew has worked with Java since 1996. Most recently he worked on the Java desktop client and enterprise servlets for Snippets Software. You can reach him at andrew@downs.ws.

 
AAPL
$109.41
Apple Inc.
+2.67
MSFT
$45.74
Microsoft Corpora
+0.58
GOOG
$504.89
Google Inc.
+9.50

MacTech Search:
Community Search:

Software Updates via MacUpdate

BBEdit 11.0.2 - Powerful text and HTML e...
BBEdit is the leading professional HTML and text editor for the Mac. Specifically crafted in response to the needs of Web authors and software developers, this award-winning product provides a... Read more
ExpanDrive 4.2.1 - Access cloud storage...
ExpanDrive builds cloud storage in every application, acts just like a USB drive plugged into your Mac. With ExpanDrive, you can securely access any remote file server directly from the Finder or... Read more
Adobe After Effects CC 2014 13.2 - Creat...
After Effects CC 2014 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous After Effects customer). After Effects CS6 is still available... Read more
Command-C 1.1.7 - Clipboard sharing tool...
Command-C is a revolutionary app which makes easy to share your clipboard between iOS and OS X using your local WiFi network, even if the app is not currently opened. Copy anything (text, pictures,... Read more
Tidy Up 4.0.2 - Find duplicate files and...
Tidy Up is a complete duplicate finder and disk-tidiness utility. With Tidy Up you can search for duplicate files and packages by the owner application, content, type, creator, extension, time... Read more
Typinator 6.3 - Speedy and reliable text...
Typinator turbo-charges your typing productivity. Type a little. Typinator does the rest. We've all faced projects that require repetitive typing tasks. With Typinator, you can store commonly used... Read more
GraphicConverter 9.5 - Graphics editor w...
GraphicConverter is an all-purpose image-editing program that can import 200 different graphic-based formats, edit the image, and export it to any of 80 available file formats. The high-end editing... Read more
Toast Titanium 12.0.1 - The ultimate med...
Toast Titanium goes way beyond the very basic burning in the Mac OS and iLife software, and sets the standard for burning CDs, DVDs, and now Blu-ray discs on the Mac. Create superior sounding audio... Read more
QuickBooks 2015 16.0.2.1422 R3 - Financi...
Save 20% on QuickBooks Pro for Mac today through this special discount link QuickBooks Pro 2013 helps you manage your business easily and efficiently. Organize your finances all in one place, track... Read more
Remotix 3.0.6 - Access all your computer...
Remotix is a fast and powerful application to easily access multiple Macs (and PCs) from your own Mac. Features: Complete Apple Screen Sharing support - including Mac OS X login, clipboard... Read more

Latest Forum Discussions

See All

Give It Up! (Games)
Give It Up! 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: GIVE IT UP is a rather hard game where you have to assist this cheerful, singing Blob in jumping through 9 different tracks.So far... | Read more »
The Drive : Devil's Run (Games)
The Drive : Devil's Run 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: ON THE ROAD AGAIN! The Drive - Devil’s Run is classic point to point style racing game that pays homage to the classics... | Read more »
Procreate Pocket (Entertainment)
Procreate Pocket 1.01 Device: iOS iPhone Category: Entertainment Price: $2.99, Version: 1.01 (iTunes) Description: Create - anytime, anywhere. Made by the developers of the award-winning Procreate® for iPad®, Procreate Pocket™ allows... | Read more »
IRON FINGER - Mini Games Championship (...
IRON FINGER - Mini Games Championship 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Quick to play, easy to learn yet hard to master.. TAP, SWIPE & TILT your way through mini games that... | Read more »
Pentaction: Medieval (Games)
Pentaction: Medieval 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Pentaction: Medieval is a turn-based strategy board-game about chance and skill on the battlefield. Take control of your... | Read more »
Hipstify Review
Hipstify Review By Jennifer Allen on December 17th, 2014 Our Rating: :: COOL FILTERSUniversal App - Designed for iPhone and iPad Add filters, quotes, and fancy frames to your images, thanks to Hipstify.   | Read more »
Mighty Smighties Gets Evolve Cards and N...
Mighty Smighties Gets Evolve Cards and New Worlds Posted by Jessica Fisher on December 17th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Duckie Deck Card Wars Review
Duckie Deck Card Wars Review By Amy Solomon on December 17th, 2014 Our Rating: :: STYLISH GAME OF CARDSUniversal App - Designed for iPhone and iPad Duckie Deck Card Wars adapts the classic card game War for use on devices, complete... | Read more »
PDF Office Review
PDF Office Review By Jennifer Allen on December 17th, 2014 Our Rating: :: CONVENIENT PDF EDITINGiPad Only App - Designed for the iPad Want to create your own PDF files? Import them from elsewhere? Adapt a web page into a PDF? PDF... | Read more »
The Out There: Ω Edition Update will be...
The Out There: Ω Edition Update will be Releasing in 2015, Bringing Better Graphics and Additional Content Posted by Jessica Fisher on December 17th, 2014 [ permalink ] | Read more »

Price Scanner via MacPrices.net

Amazon offers 15-inch 2.2GHz Retina MacBook P...
 Amazon.com has the 15″ 2.2GHz Retina MacBook Pro on sale for $1699 including free shipping. Their price is $300 off MSRP. Stock is limited, so act now if you’re interested. Read more
Holiday sales continue: MacBook Pros for up t...
 B&H Photo has new MacBook Pros on sale for up to $300 off MSRP as part of their Holiday pricing. Shipping is free, and B&H charges NY sales tax only: - 15″ 2.2GHz Retina MacBook Pro: $1699... Read more
Google Search App For iOS Gets A Major Makeov...
Google has given iOS users an early Christmas present with a substantial update of it’s not-very-often-upgraded Google Search app. Google Search has been my go-to tool for Web searches since it was... Read more
ShopKeep Apple Pay And Chip Card Reader Avail...
ShopKeep, a cloud-based technology provider to more than 10,000 small business owners to manage retail shops and restaurants with iPads, has released its new Apple Pay and chip card reader. This... Read more
Holiday sale! 27-inch 5K iMac for $2299, save...
 B&H Photo has the 27″ 3.5GHz 5K iMac in stock today and on sale for $2299 including free shipping plus NY sales tax only. Their price is $200 off MSRP, and it’s the lowest price available for... Read more
Holiday Sale! 3.7GHz Quad Core Mac Pro availa...
 B&H Photo has the 3.7GHz Quad Core Mac Pro on sale for $2599 including free shipping plus NY sales tax only. Their price is $400 off MSRP, and it’s the lowest price for this model from any... Read more
iPhone 6 Number 3 Canadian Google Search Of 2...
CTVNews.ca reports that Apple’s iPhone 6 was the third highest-trending Google Canada search topic of 2014, exceeded only by Robin Williams largely after his death by suicide in August, and the FIFA... Read more
New iPad mini 3 Counter-Top & Wall Mount...
newMacgadgets has announced new secure all-acrylic displays for the iPad mini 3 (also works fine with the mini 2, last year’s iPad mini With Retina Display, and the original iPad mini). The new iPad... Read more
Holiday sales continue, MacBook Airs for up t...
B&H Photo has 2014 MacBook Airs on sale for up to $120 off MSRP, for a limited time, for the Thanksgiving/Christmas Holiday shopping season. Shipping is free, and B&H charges NY sales tax... Read more
B&H lowers price on 27-inch 3.2GHz iMac t...
B&H Photo has lowered their price on the 27″ 3.2GHz iMac, now on sale for $1629 including free shipping plus NY sales tax only. Their price is $170 off MSRP, and it’s the lowest price for this... Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Project Manager / Business Analyst, WW *Appl...
…a senior project manager / business analyst to work within our Worldwide Apple Fulfillment Operations and the Business Process Re-engineering team. This role will work Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.