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();
}
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.
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"
}
Thursday, May 28, 2009
Generate hex string unique random ID
The code below is used to generate unique random ID in varchar with 10 chars in length. Though checking whether the ID generated had been used before in the table before inserting is still required, the probability of colliding ID is very low.
public String generateId() throws NoSuchAlgorithmException {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte [] bytes = new byte[5];
random.nextBytes(bytes);
return byteArrayToHex(bytes);
}
public String byteArrayToHex(byte[] bytes) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
String theHex = Integer.toHexString(bytes[i] & 0xFF).toUpperCase();
sb.append(theHex.length() == 1 ? "0" + theHex : theHex);
}
return sb.toString();
}
Wednesday, May 20, 2009
Test unit servlet using Jetty's ServletTester
Unit testing servlet classes is easier done with Jetty's ServletTester. This class can be found in package
First setup ServletTester instance, calling start method will run Jetty webserver in unoccupied port.
Now we're ready to test our servlet. Since in test mode all call is simulated, no browser application needed. Using HttpTester we can create request response object to simulate this. The important here is to add header "HOST" with value "tester" so the request get received by ServletTester initialized above.
Here is example to create POST method request to servlet.
Finally test the response object using assert.
HttpTester also has getContent() method, testing the content returned can be done using regular expression matching, or use XMLUnit parser to easier the task.
To summarize, here is sample utility method to construct the request above.
import org.mortbay.jetty.testing.* by adding jetty-servlet-tester-xxx.jar where xxx is the Jetty's version.First setup ServletTester instance, calling start method will run Jetty webserver in unoccupied port.
tester = new ServletTester();
tester.setContextPath("/");
tester.addServlet(MyServlet.class, "/my_servlet");
baseUrl = tester.createSocketConnector(true);
tester.start();
Now we're ready to test our servlet. Since in test mode all call is simulated, no browser application needed. Using HttpTester we can create request response object to simulate this. The important here is to add header "HOST" with value "tester" so the request get received by ServletTester initialized above.
Here is example to create POST method request to servlet.
HttpTester req = new HttpTester();
HttpTester resp = new HttpTester();
req.setMethod("POST");
req.setHeader("HOST", "tester");
req.setURI("/my_servlet");
req.setContent("name=value&name2=value2);
resp.parse(tester.getResponses(req.generate()));
Finally test the response object using assert.
assertEquals(200, resp.getStatus());
HttpTester also has getContent() method, testing the content returned can be done using regular expression matching, or use XMLUnit parser to easier the task.
To summarize, here is sample utility method to construct the request above.
public HttpTester executeWeb(String method, String uri, Mapparams, Map headers, String content) throws IOException, Exception {
HttpTester req = new HttpTester();
HttpTester resp = new HttpTester();
// set header
if (headers != null) {
Iteratorit = headers.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
String value = headers.get(key);
req.setHeader(key, value);
}
}
if (params != null) {
if (method.equalsIgnoreCase("post"))
content = mapToParameter(params);
else if (uri.contains("?"))
uri += "&" + mapToParameter(params);
else
uri += "?" + mapToParameter(params);
}
req.setMethod(method);
req.setHeader("HOST", "tester");
req.setURI(uri);
req.setContent(content);
resp.parse(tester.getResponses(req.generate()));
return resp;
}
Monday, May 18, 2009
Run servlet using Jetty
Jetty is embedded server, unlike tomcat it is simple yet powerful to host even in your production site. Jetty is also perfect to run you servlet in your local computer during development, and makes debugging webapp easier.
In main class import these classes
In main method create Server and Context class then add servlet classes to context instance.
Open browser and enter url http://localhost:8080/mycontext/url-map
In main class import these classes
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
In main method create Server and Context class then add servlet classes to context instance.
Server server = new Server(8080);
Context root;
root = new Context(server, "/mycontext", Context.SESSIONS);
root.addServlet(MyServlet.class, "/url-map");
server.start();
Open browser and enter url http://localhost:8080/mycontext/url-map
Sunday, May 17, 2009
Extending Java apps using Groovy
Using groovy it's possible to create class that implements interface written in Java. Groovy syntax also inherited from Java syntax thus you can move your existing java code into groovy with minimal changes.
Here is how to produce class from Groovy script.
It is possible to put class object (clazz instance in above example) into cache system to enhance performace.
Warn! You need to watch for your app performance on high trafic system and extend your application cautiously.
Here is how to produce class from Groovy script.
File scriptFile = new File("implementation.groovy");
GroovyClassLoader gcl = new GroovyClassLoader();
Class clazz = gcl.parseClass(scriptFile);
Object object = clazz.newInstance();
It is possible to put class object (clazz instance in above example) into cache system to enhance performace.
Warn! You need to watch for your app performance on high trafic system and extend your application cautiously.
Subscribe to:
Posts (Atom)