1 4 package demo.sharedqueue; 5 6 import java.io.IOException ; 7 import java.io.OutputStream ; 8 import org.mortbay.http.HttpContext; 9 import org.mortbay.http.HttpException; 10 import org.mortbay.http.HttpHandler; 11 import org.mortbay.http.HttpRequest; 12 import org.mortbay.http.HttpResponse; 13 14 public class SimpleHttpHandler 15 implements HttpHandler { 16 17 private boolean started = false; 18 private HttpContext context; 19 private Queue queue; 20 private final String htmlPath; 21 24 public static final String ACTION = "/webapp/"; 25 28 public static final String UNITS_OF_WORK = "unitsOfWork"; 29 30 34 public SimpleHttpHandler(Queue queue, String htmlPath) { 35 this.queue = queue; 36 this.htmlPath = htmlPath; 37 } 38 39 42 public String getName() { 43 return "Simple Http Handler"; 44 } 45 46 49 public HttpContext getHttpContext() { 50 return context; 51 } 52 53 56 public boolean isStarted() { 57 return started; 58 } 59 60 68 public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) 69 throws HttpException, IOException { 70 if (pathInContext.equals("/add_work_item.asp")) { 71 final int unitsOfWork = getIntForParameter(request, UNITS_OF_WORK); 72 Thread processor = new Thread ( 73 new Runnable () { 74 public void run() { 75 for (int i = 0; i < unitsOfWork; i++) { 76 queue.addJob(); 77 try { 78 Thread.sleep(50); 79 } 80 catch (InterruptedException ie) { 82 System.err.println(ie.getMessage()); 83 } 84 } 85 } 86 }); 87 processor.start(); 88 response.sendRedirect(ACTION); 89 } 90 91 else if (pathInContext.equals("/get_info_xml.asp")) { 92 response.setContentType("text/xml"); 93 response.setField("Cache-Control", "no-cache"); 94 OutputStream os = response.getOutputStream(); 95 os.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>".getBytes()); 96 os.write("<root>".getBytes()); 97 os.write(queue.getXmlData().getBytes()); 98 os.write("</root>".getBytes()); 99 response.commit(); 100 request.setHandled(true); 101 } 102 } 103 104 107 public void initialize(HttpContext initContext) { 108 this.context = initContext; 109 } 110 111 114 public void start() 115 throws Exception { 116 this.started = true; 117 } 118 119 121 public void stop() { 122 started = false; 123 } 124 125 130 private int getIntForParameter(HttpRequest request, String name) { 131 String param = request.getParameter(name); 132 try { 133 return param == null ? 0 : Integer.parseInt(param); 134 } 135 catch (NumberFormatException nfe) { 136 return 0; 137 } 138 } 139 } 140 | Popular Tags |