KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openi > web > RequestFilter


1 /*********************************************************************************
2  * The contents of this file are subject to the OpenI Public License Version 1.0
3  * ("License"); You may not use this file except in compliance with the
4  * License. You may obtain a copy of the License at
5  * http://www.openi.org/docs/LICENSE.txt
6  *
7  * Software distributed under the License is distributed on an "AS IS" basis,
8  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
9  * the specific language governing rights and limitations under the License.
10  *
11  * The Original Code is: OpenI Open Source
12  *
13  * The Initial Developer of the Original Code is Loyalty Matrix, Inc.
14  * Portions created by Loyalty Matrix, Inc. are
15  * Copyright (C) 2005 Loyalty Matrix, Inc.; All Rights Reserved.
16  *
17  * Contributor(s): ______________________________________.
18  *
19  ********************************************************************************/

20 package org.openi.web;
21
22 import com.tonbeller.tbutils.testenv.Environment;
23 import com.tonbeller.wcf.controller.Controller;
24 import com.tonbeller.wcf.controller.MultiPartEnabledRequest;
25 import com.tonbeller.wcf.controller.RequestContext;
26 import com.tonbeller.wcf.controller.RequestContextFactoryFinder;
27 import com.tonbeller.wcf.controller.RequestSynchronizer;
28 import com.tonbeller.wcf.controller.WcfController;
29 import com.tonbeller.wcf.utils.DomUtils;
30 import com.tonbeller.wcf.utils.JDK13Utils;
31 import com.tonbeller.wcf.utils.UrlUtils;
32 import org.apache.log4j.Logger;
33 import org.apache.log4j.MDC;
34 import java.io.IOException JavaDoc;
35 import java.io.PrintWriter JavaDoc;
36 import javax.servlet.Filter JavaDoc;
37 import javax.servlet.FilterChain JavaDoc;
38 import javax.servlet.FilterConfig JavaDoc;
39 import javax.servlet.ServletException JavaDoc;
40 import javax.servlet.ServletRequest JavaDoc;
41 import javax.servlet.ServletResponse JavaDoc;
42 import javax.servlet.http.HttpServletRequest JavaDoc;
43 import javax.servlet.http.HttpServletResponse JavaDoc;
44 import javax.servlet.http.HttpSession JavaDoc;
45 import javax.servlet.jsp.jstl.core.Config;
46
47
48 /**
49  * Based on the orignal RequestFilter from jpivot. This one is modified to prevent the
50  * busy page, prevent writing the error directly to stream, and other
51  * nuisances caused by the classes predecessor.
52  */

53 public class RequestFilter implements Filter JavaDoc {
54     private static Logger logger = Logger.getLogger(RequestFilter.class);
55     static final String JavaDoc NEXTVIEW = RequestFilter.class.getName() + ".nextview";
56     static final String JavaDoc ISNEW = RequestFilter.class.getName() + ".isnew";
57
58     /** Name of the Request Attribute containing the Request.getRequestURI */
59     public static final String JavaDoc CONTEXT = "context";
60
61     /** if the session attribute FORCE_INDEX_JSP exists, then the client will be redirected to index.jsp */
62     public static final String JavaDoc FORCE_INDEX_JSP = "com.tonbeller.wcf.controller.FORCE_INDEX_JSP";
63
64     /**
65      * If this request parameter is present, the DomUtils.randomId()
66      * will be reset once.
67      */

68     public static final String JavaDoc RESET_RANDOM_SEED = "resetRandomSeed";
69     private String JavaDoc errorJSP = null;
70     private String JavaDoc busyJSP = null;
71     private String JavaDoc indexJSP = null;
72     private String JavaDoc[] passThru = null;
73     private String JavaDoc forceExtension = null;
74
75     public RequestFilter() {
76     }
77
78     public void init(FilterConfig JavaDoc config) throws ServletException JavaDoc {
79         errorJSP = config.getInitParameter("errorJSP");
80         forceExtension = config.getInitParameter("forceExtension");
81         indexJSP = config.getInitParameter("indexJSP");
82         busyJSP = config.getInitParameter("busyJSP");
83
84         String JavaDoc patternList = config.getInitParameter("passThru");
85         passThru = UrlUtils.parseUrlPatternList(patternList);
86     }
87
88     public void doFilter(ServletRequest JavaDoc req, ServletResponse JavaDoc res,
89         FilterChain JavaDoc chain) throws IOException JavaDoc, ServletException JavaDoc {
90         MultiPartEnabledRequest request = new MultiPartEnabledRequest((HttpServletRequest JavaDoc) req);
91         HttpServletResponse JavaDoc response = (HttpServletResponse JavaDoc) res;
92
93         HttpSession JavaDoc session = request.getSession(true);
94         MDC.put("SessionID", session.getId());
95
96         String JavaDoc cpath = request.getContextPath();
97         request.setAttribute(CONTEXT, cpath);
98
99         RequestContext context = RequestContextFactoryFinder.createContext(request,
100                 response, true);
101
102         try {
103             // set locale for JSTL tags
104
Config.set(request, Config.FMT_LOCALE, context.getLocale());
105
106             // log if necessary
107
if (logger.isInfoEnabled()) {
108                 logRequest(request);
109             }
110
111             if (passThru(req)) {
112                 chain.doFilter(req, res);
113
114                 return;
115             }
116
117             MyHandler handler = new MyHandler(context, chain);
118             long t1 = System.currentTimeMillis();
119             RequestSynchronizer.instance(request).handleRequest(handler);
120
121             long t2 = System.currentTimeMillis();
122
123             if (logger.isInfoEnabled()) {
124                 logger.info("Request Execution total time: " + (t2 - t1)
125                     + " ms");
126             }
127         } catch (Throwable JavaDoc e) {
128             logger.error(e);
129
130             // removed the writing directly to stream
131
throw new ServletException JavaDoc("my servlet exception: " + e, e);
132         } finally {
133             context.invalidate();
134         }
135     }
136
137     private boolean passThru(ServletRequest JavaDoc req) {
138         if (passThru == null) {
139             return false;
140         }
141
142         HttpServletRequest JavaDoc hsr = (HttpServletRequest JavaDoc) req;
143
144         return UrlUtils.matchPattern(hsr, passThru);
145     }
146
147     /** for testing */
148     void setForceExtension(String JavaDoc forceExtension) {
149         this.forceExtension = forceExtension;
150     }
151
152     private void logRequest(HttpServletRequest JavaDoc request) {
153         logger.info(">>> Request " + request.getScheme() + "://"
154             + request.getServerName() + ":" + request.getServerPort()
155             + request.getContextPath() + request.getServletPath() + "["
156             + request.getPathInfo() + "]" + "[?" + request.getQueryString()
157             + "]");
158     }
159
160     public static void setSessionIsNew(HttpSession JavaDoc session, boolean isNew) {
161         session.setAttribute(ISNEW, Boolean.toString(isNew));
162     }
163
164     public static void setForceIndexJsp(HttpSession JavaDoc session, boolean b) {
165         if (b) {
166             session.setAttribute(FORCE_INDEX_JSP, "true");
167         } else {
168             session.removeAttribute(FORCE_INDEX_JSP);
169         }
170     }
171
172     public void destroy() {
173     }
174
175     class MyHandler implements RequestSynchronizer.Handler {
176         protected RequestContext context;
177         protected HttpServletRequest JavaDoc request;
178         protected HttpServletResponse JavaDoc response;
179         protected FilterChain JavaDoc filterChain;
180
181         public MyHandler(RequestContext context, FilterChain JavaDoc filterChain) {
182             this.context = context;
183             this.request = context.getRequest();
184             this.response = context.getResponse();
185             this.filterChain = filterChain;
186         }
187
188         public String JavaDoc getResultURI() {
189             // did the controller change the view?
190
String JavaDoc uri = (String JavaDoc) request.getAttribute(NEXTVIEW);
191
192             if (uri != null) {
193                 uri = UrlUtils.forceExtension(uri, forceExtension);
194                 uri = UrlUtils.redirectURI(request, uri);
195
196                 return uri;
197             }
198
199             // no, redisplay the current request
200
return request.getRequestURI();
201         }
202
203         public void normalRequest() throws Exception JavaDoc {
204             HttpSession JavaDoc session = request.getSession(true);
205
206             if (request.getParameter(RESET_RANDOM_SEED) != null) {
207                 DomUtils.setRandomSeed(123);
208             }
209
210             if (redirectToIndex()) {
211                 return;
212             }
213
214             // fire events
215
Controller controller = WcfController.instance(session);
216             controller.request(context);
217
218             // someone has called sendRedirect() on the response?
219
if (response.containsHeader("Location")) {
220                 return;
221             }
222
223             // someone has called sendError() or sendRedirect() on the response?
224
if (context.isResponseComplete()) {
225                 return;
226             }
227
228             // The current page is redisplayed unless there was an error
229
// in which case we go to the start page.
230
String JavaDoc uri = (String JavaDoc) request.getAttribute(NEXTVIEW);
231
232             if (session.getAttribute(FORCE_INDEX_JSP) != null) {
233                 session.removeAttribute(FORCE_INDEX_JSP);
234                 uri = indexJSP;
235             }
236
237             if (uri != null) {
238                 forward(uri);
239             } else {
240                 filterChain.doFilter(request, response);
241             }
242         }
243
244         public void recursiveRequest() throws Exception JavaDoc {
245             filterChain.doFilter(request, response);
246         }
247
248         public void showBusyPage(boolean redirect) throws Exception JavaDoc {
249             /*
250                if (redirectToIndex())
251                  return;
252                if (busyJSP != null) {
253                  if (redirect)
254                    forward(busyJSP);
255                  else
256                    filterChain.doFilter(request, response);
257                } else
258                  throw new IllegalStateException("concurrent requests and no busy.jsp defined in web.xml");
259              */

260
261             //forget this busy stuff
262
filterChain.doFilter(request, response);
263         }
264
265         public boolean isBusyPage() {
266             if (busyJSP == null) {
267                 return false;
268             }
269
270             return request.getRequestURI().endsWith(busyJSP);
271         }
272
273         /**
274          * @param uri
275          * @throws IOException
276          */

277         private void forward(String JavaDoc uri) throws IOException JavaDoc {
278             uri = UrlUtils.redirectURI(request, uri);
279             uri = UrlUtils.forceExtension(uri, forceExtension);
280
281             if (logger.isInfoEnabled()) {
282                 logger.info("redirecting to " + uri);
283             }
284
285             response.sendRedirect(uri);
286         }
287
288         /**
289          * true, if the current request was redirected to the index page
290          * because there is no valid session.
291          */

292         protected boolean redirectToIndex() throws Exception JavaDoc {
293             if (indexJSP != null) {
294                 // do not redirect to index.jsp while testing
295
if (Environment.isTest()) {
296                     return false;
297                 }
298
299                 HttpSession JavaDoc session = context.getSession();
300                 boolean isNew = session.isNew();
301
302                 if (!isNew) {
303                     isNew = !"false".equals(session.getAttribute(ISNEW));
304                 }
305
306                 if (isNew) {
307                     session.setAttribute(ISNEW, "false");
308                     forward(indexJSP);
309
310                     return true;
311                 }
312             }
313
314             return false;
315         }
316     }
317 }
318
Popular Tags