package com.myeclipseide.asynccontext;

import java.io.IOException;
import java.util.Random;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(asyncSupported = true, urlPatterns = "/DispatcherServlet")
public class DispatcherServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public DispatcherServlet() {
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getParameter("startServ1") != null) {
			startDispatcher(request, response);
		}

	}

	public void startDispatcher(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		ServletOutputStream outputStream = response.getOutputStream();
		AsyncContext myAsyncContext = request.startAsync();
		try {
			myAsyncContext.start(new AsyncDispatcher(myAsyncContext,
					outputStream));
		} catch (Throwable th) {
			outputStream.println("Caught Throwable " + th.getLocalizedMessage()
					+ "</BR>");
		}
		Float value = new Random().nextFloat() * 1000;
		try {

			Thread.sleep(value.longValue());
		} catch (InterruptedException e) {
			outputStream.println("problem in DispatcherServlet</BR>");
			e.printStackTrace();
		}

	}
	
	

}
