KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > webapp > control > ContextFilter


1 /*
2  * $Id: ContextFilter.java 5744 2005-09-15 04:12:25Z jaz $
3  *
4  * Copyright (c) 2003 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  */

25 package org.ofbiz.webapp.control;
26
27 import java.io.IOException JavaDoc;
28 import java.net.MalformedURLException JavaDoc;
29 import java.net.URL JavaDoc;
30 import java.util.ArrayList JavaDoc;
31 import java.util.Collection JavaDoc;
32 import java.util.Enumeration JavaDoc;
33 import java.util.Iterator JavaDoc;
34 import java.util.List JavaDoc;
35 import java.util.Map 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.HttpServletResponseWrapper JavaDoc;
45
46 import org.ofbiz.base.container.ContainerLoader;
47 import org.ofbiz.base.start.StartupException;
48 import org.ofbiz.base.util.CachedClassLoader;
49 import org.ofbiz.base.util.Debug;
50 import org.ofbiz.base.util.StringUtil;
51 import org.ofbiz.base.util.UtilHttp;
52 import org.ofbiz.base.util.UtilValidate;
53 import org.ofbiz.base.util.UtilObject;
54 import org.ofbiz.entity.GenericDelegator;
55 import org.ofbiz.security.Security;
56 import org.ofbiz.security.SecurityConfigurationException;
57 import org.ofbiz.security.SecurityFactory;
58 import org.ofbiz.service.LocalDispatcher;
59 import org.ofbiz.service.WebAppDispatcher;
60
61 /**
62  * ContextFilter - Restricts access to raw files and configures servlet objects.
63  *
64  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
65  * @version $Rev: 5744 $
66  * @since 2.2
67  */

68 public class ContextFilter implements Filter JavaDoc {
69
70     public static final String JavaDoc module = ContextFilter.class.getName();
71     public static final String JavaDoc CONTAINER_CONFIG = "limited-containers.xml";
72     public static final String JavaDoc FORWARDED_FROM_SERVLET = "_FORWARDED_FROM_SERVLET_";
73
74     protected ClassLoader JavaDoc localCachedClassLoader = null;
75     protected FilterConfig JavaDoc config = null;
76     protected boolean debug = false;
77
78     /**
79      * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
80      */

81     public void init(FilterConfig JavaDoc config) throws ServletException JavaDoc {
82         this.config = config;
83
84         // puts all init-parameters in ServletContext attributes for easier parameterization without code changes
85
this.putAllInitParametersInAttributes();
86
87         // initialize the cached class loader for this application
88
ClassLoader JavaDoc loader = Thread.currentThread().getContextClassLoader();
89         localCachedClassLoader = new CachedClassLoader(loader, (String JavaDoc) config.getServletContext().getAttribute("webSiteId"));
90
91         // set debug
92
this.debug = "true".equalsIgnoreCase(config.getInitParameter("debug"));
93         if (!debug) {
94             debug = Debug.verboseOn();
95         }
96
97         // load the containers
98
getContainers();
99         // check the serverId
100
getServerId();
101         // initialize the delegator
102
getDelegator();
103         // initialize security
104
getSecurity();
105         // initialize the services dispatcher
106
getDispatcher();
107
108         // this will speed up the initial sessionId generation
109
new java.security.SecureRandom JavaDoc().nextLong();
110     }
111
112     /**
113      * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
114      */

115     public void doFilter(ServletRequest JavaDoc request, ServletResponse JavaDoc response, FilterChain JavaDoc chain) throws IOException JavaDoc, ServletException JavaDoc {
116         HttpServletRequest JavaDoc httpRequest = (HttpServletRequest JavaDoc) request;
117         HttpServletResponseWrapper JavaDoc wrapper = new HttpServletResponseWrapper JavaDoc((HttpServletResponse JavaDoc) response);
118
119         // Debug.logInfo("Running ContextFilter.doFilter", module);
120

121         // ----- Servlet Object Setup -----
122
// set the cached class loader for more speedy running in this thread
123
Thread.currentThread().setContextClassLoader(localCachedClassLoader);
124
125         // set the webSiteId in the session
126
httpRequest.getSession().setAttribute("webSiteId", config.getServletContext().getAttribute("webSiteId"));
127
128         // set the ServletContext in the request for future use
129
request.setAttribute("servletContext", config.getServletContext());
130
131         // set the filesystem path of context root.
132
request.setAttribute("_CONTEXT_ROOT_", config.getServletContext().getRealPath("/"));
133
134         // set the server root url
135
StringBuffer JavaDoc serverRootUrl = UtilHttp.getServerRootUrl(httpRequest);
136         request.setAttribute("_SERVER_ROOT_URL_", serverRootUrl.toString());
137
138         // request attributes from redirect call
139
String JavaDoc reqAttrMapHex = (String JavaDoc) httpRequest.getSession().getAttribute("_REQ_ATTR_MAP_");
140         if (UtilValidate.isNotEmpty(reqAttrMapHex)) {
141             byte[] reqAttrMapBytes = StringUtil.fromHexString(reqAttrMapHex);
142             Map JavaDoc reqAttrMap = (Map JavaDoc) UtilObject.getObject(reqAttrMapBytes);
143             if (reqAttrMap != null) {
144                 Iterator JavaDoc i = reqAttrMap.keySet().iterator();
145                 while (i.hasNext()) {
146                     String JavaDoc key = (String JavaDoc) i.next();
147                     request.setAttribute(key, reqAttrMap.get(key));
148                 }
149             }
150             httpRequest.getSession().removeAttribute("_REQ_ATTR_MAP_");
151         }
152
153         // ----- Context Security -----
154
// check if we are disabled
155
String JavaDoc disableSecurity = config.getInitParameter("disableContextSecurity");
156         if (disableSecurity != null && "Y".equals(disableSecurity)) {
157             chain.doFilter(request, response);
158             return;
159         }
160
161         // check if we are told to redirect everthing
162
String JavaDoc redirectAllTo = config.getInitParameter("forceRedirectAll");
163         if (redirectAllTo != null && redirectAllTo.length() > 0) {
164             // little trick here so we don't loop on ourself
165
if (httpRequest.getSession().getAttribute("_FORCE_REDIRECT_") == null) {
166                 httpRequest.getSession().setAttribute("_FORCE_REDIRECT_", "true");
167                 Debug.logWarning("Redirecting user to: " + redirectAllTo, module);
168
169                 if (!redirectAllTo.toLowerCase().startsWith("http")) {
170                     redirectAllTo = httpRequest.getContextPath() + redirectAllTo;
171                 }
172                 wrapper.sendRedirect(redirectAllTo);
173                 return;
174             } else {
175                 httpRequest.getSession().removeAttribute("_FORCE_REDIRECT_");
176                 chain.doFilter(request, response);
177                 return;
178             }
179         }
180
181         // test to see if we have come through the control servlet already, if not do the processing
182
if (request.getAttribute(ContextFilter.FORWARDED_FROM_SERVLET) == null) {
183             // Debug.logInfo("In ContextFilter.doFilter, FORWARDED_FROM_SERVLET is NOT set", module);
184
String JavaDoc allowedPath = config.getInitParameter("allowedPaths");
185             String JavaDoc redirectPath = config.getInitParameter("redirectPath");
186             String JavaDoc errorCode = config.getInitParameter("errorCode");
187
188             List JavaDoc allowList = StringUtil.split(allowedPath, ":");
189             allowList.add("/"); // No path is allowed.
190
allowList.add(""); // No path is allowed.
191

192             if (debug) Debug.log("[Request]: " + httpRequest.getRequestURI(), module);
193
194             String JavaDoc requestPath = httpRequest.getServletPath();
195             if (requestPath == null) requestPath = "";
196             if (requestPath.lastIndexOf("/") > 0) {
197                 if (requestPath.indexOf("/") == 0) {
198                     requestPath = "/" + requestPath.substring(1, requestPath.indexOf("/", 1));
199                 } else {
200                     requestPath = requestPath.substring(1, requestPath.indexOf("/"));
201                 }
202             }
203
204             String JavaDoc requestInfo = httpRequest.getServletPath();
205             if (requestInfo == null) requestInfo = "";
206             if (requestInfo.lastIndexOf("/") >= 0) {
207                 requestInfo = requestInfo.substring(0, requestInfo.lastIndexOf("/")) + "/*";
208             }
209
210             StringBuffer JavaDoc contextUriBuffer = new StringBuffer JavaDoc();
211             if (httpRequest.getContextPath() != null) {
212                 contextUriBuffer.append(httpRequest.getContextPath());
213             }
214             if (httpRequest.getServletPath() != null) {
215                 contextUriBuffer.append(httpRequest.getServletPath());
216             }
217             if (httpRequest.getPathInfo() != null) {
218                 contextUriBuffer.append(httpRequest.getPathInfo());
219             }
220             String JavaDoc contextUri = contextUriBuffer.toString();
221
222             // Verbose Debugging
223
if (Debug.verboseOn()) {
224                 for (int i = 0; i < allowList.size(); i++) {
225                     Debug.logVerbose("[Allow]: " + allowList.get(i), module);
226                 }
227                 Debug.logVerbose("[Request path]: " + requestPath, module);
228                 Debug.logVerbose("[Request info]: " + requestInfo, module);
229                 Debug.logVerbose("[Servlet path]: " + httpRequest.getServletPath(), module);
230             }
231
232             // check to make sure the requested url is allowed
233
if (!allowList.contains(requestPath) && !allowList.contains(requestInfo) && !allowList.contains(httpRequest.getServletPath())) {
234                 String JavaDoc filterMessage = "[Filtered request]: " + contextUri;
235
236                 if (redirectPath == null) {
237                     int error = 404;
238                     try {
239                         error = Integer.parseInt(errorCode);
240                     } catch (NumberFormatException JavaDoc nfe) {
241                         Debug.logWarning(nfe, "Error code specified would not parse to Integer : " + errorCode, module);
242                     }
243                     filterMessage = filterMessage + " (" + error + ")";
244                     wrapper.sendError(error, contextUri);
245                 } else {
246                     filterMessage = filterMessage + " (" + redirectPath + ")";
247                     if (!redirectPath.toLowerCase().startsWith("http")) {
248                         redirectPath = httpRequest.getContextPath() + redirectPath;
249                     }
250                     wrapper.sendRedirect(redirectPath);
251                 }
252                 Debug.logWarning(filterMessage, module);
253                 return;
254             }
255         }
256
257         // we're done checking; continue on
258
chain.doFilter(request, response);
259     }
260
261     /**
262      * @see javax.servlet.Filter#destroy()
263      */

264     public void destroy() {
265         getDispatcher().deregister();
266         config = null;
267     }
268
269     protected LocalDispatcher getDispatcher() {
270         LocalDispatcher dispatcher = (LocalDispatcher) config.getServletContext().getAttribute("dispatcher");
271         if (dispatcher == null) {
272             GenericDelegator delegator = getDelegator();
273
274             if (delegator == null) {
275                 Debug.logError("[ContextFilter.init] ERROR: delegator not defined.", module);
276                 return null;
277             }
278             Collection JavaDoc readers = null;
279             String JavaDoc readerFiles = config.getServletContext().getInitParameter("serviceReaderUrls");
280
281             if (readerFiles != null) {
282                 readers = new ArrayList JavaDoc();
283                 List JavaDoc readerList = StringUtil.split(readerFiles, ";");
284                 Iterator JavaDoc i = readerList.iterator();
285
286                 while (i.hasNext()) {
287                     try {
288                         String JavaDoc name = (String JavaDoc) i.next();
289                         URL JavaDoc readerURL = config.getServletContext().getResource(name);
290
291                         if (readerURL != null)
292                             readers.add(readerURL);
293                     } catch (NullPointerException JavaDoc npe) {
294                         Debug.logInfo(npe, "[ContextFilter.init] ERROR: Null pointer exception thrown.", module);
295                     } catch (MalformedURLException JavaDoc e) {
296                         Debug.logError(e, "[ContextFilter.init] ERROR: cannot get URL from String.", module);
297                     }
298                 }
299             }
300             // get the unique name of this dispatcher
301
String JavaDoc dispatcherName = config.getServletContext().getInitParameter("localDispatcherName");
302
303             if (dispatcherName == null)
304                 Debug.logError("No localDispatcherName specified in the web.xml file", module);
305             dispatcher = new WebAppDispatcher(dispatcherName, delegator, readers);
306             config.getServletContext().setAttribute("dispatcher", dispatcher);
307             if (dispatcher == null)
308                 Debug.logError("[ContextFilter.init] ERROR: dispatcher could not be initialized.", module);
309         }
310         return dispatcher;
311     }
312
313     protected GenericDelegator getDelegator() {
314         GenericDelegator delegator = (GenericDelegator) config.getServletContext().getAttribute("delegator");
315         if (delegator == null) {
316             String JavaDoc delegatorName = config.getServletContext().getInitParameter("entityDelegatorName");
317
318             if (delegatorName == null || delegatorName.length() <= 0) {
319                 delegatorName = "default";
320             }
321             if (Debug.infoOn()) Debug.logInfo("[ContextFilter.init] Getting Entity Engine Delegator with delegator name " + delegatorName, module);
322             delegator = GenericDelegator.getGenericDelegator(delegatorName);
323             config.getServletContext().setAttribute("delegator", delegator);
324             if (delegator == null) {
325                 Debug.logError("[ContextFilter.init] ERROR: delegator factory returned null for delegatorName \"" + delegatorName + "\"", module);
326             }
327         }
328         return delegator;
329     }
330
331     protected Security getSecurity() {
332         Security security = (Security) config.getServletContext().getAttribute("security");
333         if (security == null) {
334             GenericDelegator delegator = (GenericDelegator) config.getServletContext().getAttribute("delegator");
335
336             if (delegator != null) {
337                 try {
338                     security = SecurityFactory.getInstance(delegator);
339                 } catch (SecurityConfigurationException e) {
340                     Debug.logError(e, "[ServiceDispatcher.init] : No instance of security imeplemtation found.", module);
341                 }
342             }
343             config.getServletContext().setAttribute("security", security);
344             if (security == null) {
345                 Debug.logError("[ContextFilter.init] ERROR: security create failed.", module);
346             }
347         }
348         return security;
349     }
350
351     protected void putAllInitParametersInAttributes() {
352         Enumeration JavaDoc initParamEnum = config.getServletContext().getInitParameterNames();
353         while (initParamEnum.hasMoreElements()) {
354             String JavaDoc initParamName = (String JavaDoc) initParamEnum.nextElement();
355             String JavaDoc initParamValue = config.getServletContext().getInitParameter(initParamName);
356             if (Debug.infoOn()) Debug.logInfo("Adding web.xml context-param to application attribute with name [" + initParamName + "] and value [" + initParamValue + "]", module);
357             config.getServletContext().setAttribute(initParamName, initParamValue);
358         }
359     }
360
361     protected String JavaDoc getServerId() {
362         String JavaDoc serverId = (String JavaDoc) config.getServletContext().getAttribute("_serverId");
363         if (serverId == null) {
364             serverId = config.getServletContext().getInitParameter("ofbizServerName");
365             config.getServletContext().setAttribute("_serverId", serverId);
366         }
367         return serverId;
368     }
369
370     protected boolean getContainers() throws ServletException JavaDoc {
371         try {
372             ContainerLoader.loadContainers(CONTAINER_CONFIG, null);
373         } catch (StartupException e) {
374             Debug.logError(e, module);
375             throw new ServletException JavaDoc("Unable to load containers; cannot start ContextFilter");
376         }
377         return true;
378     }
379 }
380
Popular Tags