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

The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »

Price Scanner via MacPrices.net

Apple is offering significant discounts on 16...
Apple has a full line of 16″ M3 Pro and M3 Max MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free... Read more
Apple HomePods on sale for $30-$50 off MSRP t...
Best Buy is offering a $30-$50 discount on Apple HomePods this weekend on their online store. The HomePod mini is on sale for $69.99, $30 off MSRP, while Best Buy has the full-size HomePod on sale... Read more
Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more

Jobs Board

Licensed Practical Nurse - Womens Imaging *A...
Licensed Practical Nurse - Womens Imaging Apple Hill - PRN Location: York Hospital, York, PA Schedule: PRN/Per Diem Sign-On Bonus Eligible Remote/Hybrid Regular Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Operating Room Assistant - *Apple* Hill Sur...
Operating Room Assistant - Apple Hill Surgical Center - Day Location: WellSpan Health, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.