1    package geekblog.filters;
2    
3    
4    import java.util.prefs.*;
5    import javax.servlet.*;
6    import javax.servlet.http.*;
7    import geekblog.*;
8    
9    
10   /**
11    * Filter to set Preferences node in request attribute. Implementation note: we
12    * also use this to hijack the first request to do DataManager initialization;
13    * see why in doFilter().
14    */
15   public class PrefsSetupFilter
16     implements Filter
17   {
18     private FilterConfig config;
19     private ServletContext context;
20     private String attributeName;
21   
22     public void init(FilterConfig config)
23     {
24       this.config = config;
25       this.context = config.getServletContext();
26   
27       attributeName = config.getInitParameter("attributeName");
28       attributeName = (attributeName == null ? "application.preferences" : attributeName);
29     }
30     public void destroy()
31     {
32     }
33   
34   
35     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
36       throws ServletException, java.io.IOException
37     {
38       String ctx = ((HttpServletRequest)request).getContextPath();
39   
40       Preferences prefs = Preferences.systemRoot().node("net/sourceforge/geekblog" + ctx);
41       request.setAttribute(attributeName, prefs);
42   
43       // This will only be true ONCE, and should be in DatabaseContextListener,
44       // but I can only get hold of the ServletContext contextPath via a request
45       // object, and since I want to partition prefs info on a per-context basis
46       // in separate Preferences nodes based on the contextPath, I have to take
47       // on a lazy-initialized tack here. I hate taking the performance hit by
48       // doing this on each and every request, but there's no helping it at this
49       // point, unfortunately. FIXME in the next Servlet release, I hope.
50       //
51       if (context.getAttribute(DataManager.KEY) == null)
52       {
53         String dataManagerClass = prefs.get("datamanager.class", "geekblog.HSQLDataManager");
54         context.log("Creating DataManager of type " + dataManagerClass);
55         
56         try
57         {
58           DataManager dm = (DataManager)(Class.forName(dataManagerClass).newInstance());
59   
60           context.setAttribute(DataManager.KEY, dm);
61   
62           dm.init(context);
63         }
64         catch (Exception e)
65         {
66           context.log(e, "*** Unanticipated error ***");
67         }
68         catch (Throwable t)
69         {
70           context.log("Throwable thrown: " + t.toString());
71         }
72       }
73   
74       chain.doFilter(request, response);
75     }
76   }
77