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.