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

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.