1 package com.acme;
2
3 import java.io.IOException;
4
5 import javax.servlet.ServletException;
6 import javax.servlet.http.HttpServlet;
7 import javax.servlet.http.HttpServletRequest;
8 import javax.servlet.http.HttpServletResponse;
9
10 import org.mortbay.util.ajax.Continuation;
11 import org.mortbay.util.ajax.ContinuationSupport;
12
13
14
15
16
17
18
19 public class CometServlet extends HttpServlet
20 {
21 public void begin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
22 {
23 request.setAttribute("org.apache.tomcat.comet",Boolean.TRUE);
24 }
25
26 public void end(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
27 {
28 synchronized(request)
29 {
30 request.removeAttribute("org.apache.tomcat.comet");
31
32 Continuation continuation=ContinuationSupport.getContinuation(request,request);
33 if (continuation.isPending())
34 continuation.resume();
35 }
36 }
37
38 public void error(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
39 {
40 end(request,response);
41 }
42
43 public boolean read(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
44 {
45 throw new UnsupportedOperationException();
46 }
47
48 protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
49 {
50 synchronized(request)
51 {
52
53
54 Continuation continuation=ContinuationSupport.getContinuation(request,request);
55
56 if (!continuation.isPending())
57 begin(request,response);
58
59 Integer timeout=(Integer)request.getAttribute("org.apache.tomcat.comet.timeout");
60 boolean resumed=continuation.suspend(timeout==null?60000:timeout.intValue());
61
62 if (!resumed)
63 error(request,response);
64 }
65 }
66
67 public void setTimeout(HttpServletRequest request, HttpServletResponse response, int timeout) throws IOException, ServletException,
68 UnsupportedOperationException
69 {
70 request.setAttribute("org.apache.tomcat.comet.timeout",new Integer(timeout));
71 }
72 }