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

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.