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.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.