Friday, June 26, 2009

Jetty Handler with NIO and Continuation

After getting the http or https request through SelectChannelConnector or SslSelectChannelConnector, the custom handler method that you extend from AbstractHandler handle(...) will run.
public void handle(String target,
HttpServletRequest request,
HttpServletResponse response,
int dispatch)
throws IOException,
ServletException {

// Obtain Jetty continuation
Continuation continuation = getContinuation(request, null);

// Create a custom callback and store it in each HttpServletRequest
// This callback is to wrap the continuation object for the other thread
// to call continuation.resume() for generating the response.
// "callback" should be a final static variable in production server.
Callback callback = (Callback) request.getAttribute("callback");
if (callback == null) {
callback = new Callback(continuation);
request.setAttribute("callback", callback);
}

// Synchronize on callback to prevent continuation.resume() from
// happening before continuation.suspend().
synchronized (callback) {
if (continuation.isNew()) {
// Dispatch the request to another area with different thread
// and of course, callback must be referenced later to call
// continuation.setObject() and continuation.resume() down the road.
}
// zero here for the simplicity
continuation.suspend(0);
}

// Up to this point, the continuation is resumed, and got the object ready
// for response.
PrintWriter out = null;
try {
out = response.getWriter();
Object obj = continuation.getObject();
// further processing the obj for the "out"
} finally {
if (out != null) {
out.close();
}

// Reset the continuation
continuation.reset();
continuation.setObject(null);
}
}

No comments: