Monday, June 15, 2009

Print Stack Trace to String object

Stack trace is essential in finding errors in your program, but printing stack trace to standard output might not be what we always want. This simple method will buffer the stack trace print output to String object.


public static String getStackTrace(Throwable t)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
t.printStackTrace(pw);
pw.flush();
sw.flush();
return sw.toString();
}

Sunday, June 14, 2009

Parsing HTML using XMLUnit

XMLUnit HTML document builder is useful outside the testing environment if you want to parse HTML files using DOM model. It also supports powerful XPath engine to makes html traversing easier. Here is sample code to fetch all anchor link tag which has href attribute defined.


TolerantSaxDocumentBuilder tolerantSaxDocumentBuilder = new TolerantSaxDocumentBuilder(XMLUnit.getTestParser());
HTMLDocumentBuilder htmlDocumentBuilder = new HTMLDocumentBuilder(tolerantSaxDocumentBuilder);
Document doc = htmlDocumentBuilder.parse(content);

XpathEngine engine = XMLUnit.newXpathEngine();
String res = engine.evaluate( "/html/body//a[@href]", doc);

Friday, June 5, 2009

Regex and closure in Groovy

Simple code to match string using regex and closure in Groovy.


// text match: group1_group_2
(text =~ /(\w+)_(\w+)/).each{ all, group1, group2 ->
println "$group1 $group2"
}