01: /*
02: @COPYRIGHT@
03: */
04: package demo.sharedqueue;
05:
06: import java.io.IOException;
07:
08: import javax.servlet.ServletException;
09: import javax.servlet.http.HttpServletRequest;
10: import javax.servlet.http.HttpServletResponse;
11:
12: import org.mortbay.jetty.HttpConnection;
13: import org.mortbay.jetty.Request;
14: import org.mortbay.jetty.handler.AbstractHandler;
15:
16: public class SimpleHttpHandler extends AbstractHandler {
17:
18: private final demo.sharedqueue.Queue queue;
19:
20: public final static String ACTION = "/webapp";
21:
22: public final static String ACTION_ADDWORK = "/addWork";
23:
24: public final static String ACTION_GETINFO = "/getInfo";
25:
26: public final static String UNITS_OF_WORK = "unitsOfWork";
27:
28: public SimpleHttpHandler(Queue queue) {
29: this .queue = queue;
30: }
31:
32: private final int getIntForParameter(HttpServletRequest request,
33: final String name) {
34: String param = request.getParameter(name);
35: try {
36: return param == null ? 0 : Integer.parseInt(param);
37: } catch (NumberFormatException nfe) {
38: return 0;
39: }
40: }
41:
42: public final void handle(String target, HttpServletRequest request,
43: HttpServletResponse response, int dispatch)
44: throws IOException, ServletException {
45: Request base_request = (request instanceof Request) ? (Request) request
46: : HttpConnection.getCurrentConnection().getRequest();
47: if (target.equals(ACTION_ADDWORK)) {
48: doAddWork(base_request, response);
49: } else if (target.equals(ACTION_GETINFO)) {
50: doGetInfo(base_request, response);
51: }
52: }
53:
54: private final void doAddWork(Request request,
55: HttpServletResponse response) throws IOException {
56: final int unitsOfWork = getIntForParameter(request,
57: UNITS_OF_WORK);
58: final Thread processor = new Thread(new Runnable() {
59: public void run() {
60: for (int i = 0; i < unitsOfWork; i++) {
61: queue.addJob();
62: // added slight delay to improve visuals
63: try {
64: Thread.sleep(50);
65: } catch (InterruptedException ie) {
66: System.err.println(ie.getMessage());
67: }
68: }
69: }
70: });
71: processor.start();
72: response.sendRedirect(ACTION);
73: }
74:
75: private final void doGetInfo(Request request,
76: HttpServletResponse response) throws IOException {
77: response.setContentType("text/xml");
78: response.setStatus(HttpServletResponse.SC_OK);
79: response
80: .getWriter()
81: .println(
82: "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
83: response.getWriter().println("<root>");
84: response.getWriter().println(queue.getXmlData());
85: response.getWriter().println("</root>");
86: request.setHandled(true);
87: }
88: }
|