KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jfun > yan > web > HttpPool


1 package jfun.yan.web;
2
3 import javax.servlet.http.HttpServletRequest JavaDoc;
4 import javax.servlet.http.HttpSession JavaDoc;
5
6 import jfun.yan.factory.Pool;
7 import jfun.yan.factory.SimplePool;
8
9
10 /**
11  * This class provides thread scope and session scope pool
12  * that can be used to cache component instance.
13  * <p>
14  * @author Ben Yu
15  * Feb 1, 2006 10:54:12 PM
16  */

17 final class HttpPool {
18   private final ThreadLocal JavaDoc current_request = new InheritableThreadLocal JavaDoc();
19
20   public void setRequest(HttpServletRequest JavaDoc req){
21     current_request.set(req);
22   }
23   private HttpServletRequest JavaDoc getRequest(){
24     final Object JavaDoc r = current_request.get();
25     if(r==null){
26       throw new IllegalStateException JavaDoc("no current HttpRequest available.");
27     }
28     return (HttpServletRequest JavaDoc)r;
29   }
30   private HttpSession JavaDoc getSession(){
31     return getRequest().getSession();
32   }
33   public void setCurrentRequest(HttpServletRequest JavaDoc req){
34     current_request.set(req);
35   }
36   public Pool getRequestPool(String JavaDoc key){
37     return new RequestPool(key);
38   }
39   public Pool getSessionPool(String JavaDoc key){
40     return new SessionPool(key);
41   }
42   private final class RequestPool extends SimplePool{
43     private final String JavaDoc key;
44     
45     RequestPool(String JavaDoc key) {
46       this.key = key;
47     }
48
49     public Object JavaDoc get() {
50       return getRequest().getAttribute(key);
51     }
52
53     public void set(Object JavaDoc v){
54       getRequest().setAttribute(key, v);
55     }
56     protected Object JavaDoc getMutex(){
57       return getRequest();
58     }
59   }
60   private final class SessionPool extends SimplePool{
61     private final String JavaDoc key;
62     
63     SessionPool(String JavaDoc key) {
64       this.key = key;
65     }
66
67     public Object JavaDoc get() {
68       return getSession().getAttribute(key);
69     }
70
71     public void set(Object JavaDoc v){
72       getSession().setAttribute(key, v);
73     }
74     /**
75      * This is not guaranteed to be safe. Better than nothing.
76      */

77     protected Object JavaDoc getMutex(){
78       return getSession();
79     }
80   }
81 }
82
Popular Tags