1 package example; 2 3 import java.io.IOException ; 4 5 import java.util.logging.Level ; 6 import java.util.logging.Logger ; 7 8 import javax.servlet.*; 9 import javax.servlet.http.*; 10 11 24 public class PeriodicTaskFilter implements Filter { 25 static protected final Logger log = 26 Logger.getLogger(PeriodicTaskFilter.class.getName()); 27 28 private String _url = null; 29 private int _minEstimatedTime = 5;; 30 31 private PeriodicTask _periodicTask; 32 33 public PeriodicTaskFilter() 34 { 35 } 36 37 public void setPeriodicTask(PeriodicTask periodicTask) 38 { 39 _periodicTask = periodicTask; 40 } 41 42 46 public void setUrl(String url) 47 { 48 _url = url; 49 } 50 51 55 public void setMinEstimatedTime(int seconds) 56 { 57 _minEstimatedTime = seconds; 58 } 59 60 public void init(FilterConfig filterConfig) 61 throws ServletException 62 { 63 String p; 64 65 p = filterConfig.getInitParameter("url"); 66 if (p != null) 67 setUrl(p); 68 69 p = filterConfig.getInitParameter("min-estimated-time"); 70 if (p != null) 71 setMinEstimatedTime(Integer.parseInt(p)); 72 73 if (_periodicTask == null) 74 throw new ServletException("`period-task' is required"); 75 } 76 77 public void doFilter(ServletRequest request, 78 ServletResponse response, 79 FilterChain chain) 80 throws ServletException, IOException 81 { 82 if (_periodicTask.isActive()) { 83 dispatch( (HttpServletRequest) request, (HttpServletResponse) response); 84 } 85 else { 86 chain.doFilter(request,response); 87 } 88 } 89 90 94 protected void dispatch(HttpServletRequest request, HttpServletResponse response) 95 throws ServletException, IOException 96 { 97 long remaining = _periodicTask.getEstimatedTimeRemaining(); 98 99 remaining = ( (1000L + remaining) / 1000L ) - 1; 101 102 if (remaining < _minEstimatedTime) 103 remaining = _minEstimatedTime; 104 105 response.addHeader("Cache-Control", "max-age=" + remaining); 106 response.addHeader("refresh", String.valueOf(remaining)); 107 108 if (_url != null) 109 request.getRequestDispatcher(_url).forward(request,response); 110 else 111 response.sendError(response.SC_SERVICE_UNAVAILABLE); 112 } 113 114 public void destroy() 115 { 116 } 117 } 118 119 | Popular Tags |