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 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, Map params, Map headers, String content) throws IOException, Exception {
HttpTester req = new HttpTester();
HttpTester resp = new HttpTester();

// set header
if (headers != null) {
Iterator it = 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

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.


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.