DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Really Poor Man's Seaside
// A demo of how do continuation based web development in Java
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
public class PoorMansSeaSide extends HttpServlet
{
Thread thread;
String body;
String answer;
Object parent = new Object();
Object self = new Object();
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException
{
String answer = httpServletRequest.getParameter("answer");
if(answer != null)
{
callContinuation(answer);
}
else
{
wrapMain(httpServletRequest, httpServletResponse);
}
try
{
synchronized(parent) {
parent.wait();
}
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
httpServletResponse.setContentType("text/html");
httpServletResponse.getWriter().print("<html><body>" + body + "</body></html>");
}
private void callContinuation(String answer)
{
this.answer = answer;
synchronized(self) {
self.notify();
}
}
private String ask(String question)
{
body = question + "<br/> " +
"<form> " +
" <input type=\"text\" name=\"answer\"> " +
" <input type=\"submit\" value=\"submit\"> " +
"</form>";
synchronized(parent){
parent.notify();
}
try
{
synchronized(self) {
self.wait();
}
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
return answer;
}
private void wrapMain(HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse)
{
thread = new Thread(new Runnable(){
public void run()
{
body = main();
synchronized(parent){
parent.notify();
}
}
});
thread.start();
}
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException
{
doGet(httpServletRequest, httpServletResponse);
}
private String main()
{
String name = ask("Name?");
String age = ask("Age?");
String homeTown = ask("Home Town?");
return "Hello " + name + ". You are a " + age + " year old from " + homeTown + ".";
}
}




