KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * $Id: ControlServlet.java 5462 2005-08-05 18:35:48Z jonesde $
3  *
4  * Copyright (c) 2001-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 package org.ofbiz.webapp.control;
25
26 import javax.servlet.RequestDispatcher JavaDoc;
27 import javax.servlet.ServletConfig JavaDoc;
28 import javax.servlet.ServletContext JavaDoc;
29 import javax.servlet.ServletException JavaDoc;
30 import javax.servlet.http.HttpServlet JavaDoc;
31 import javax.servlet.http.HttpServletRequest JavaDoc;
32 import javax.servlet.http.HttpServletResponse JavaDoc;
33 import javax.servlet.http.HttpSession JavaDoc;
34 import java.io.IOException JavaDoc;
35 import java.util.Enumeration JavaDoc;
36
37 import com.ibm.bsf.BSFManager;
38
39 import org.ofbiz.base.util.Debug;
40 import org.ofbiz.base.util.UtilHttp;
41 import org.ofbiz.base.util.UtilJ2eeCompat;
42 import org.ofbiz.base.util.UtilTimer;
43 import org.ofbiz.base.util.UtilValidate;
44 import org.ofbiz.entity.GenericDelegator;
45 import org.ofbiz.entity.GenericValue;
46 import org.ofbiz.entity.transaction.GenericTransactionException;
47 import org.ofbiz.entity.transaction.TransactionUtil;
48 import org.ofbiz.security.Security;
49 import org.ofbiz.service.LocalDispatcher;
50 import org.ofbiz.webapp.stats.ServerHitBin;
51
52 /**
53  * ControlServlet.java - Master servlet for the web application.
54  *
55  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
56  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
57  * @version $Rev: 5462 $
58  * @since 2.0
59  */

60 public class ControlServlet extends HttpServlet JavaDoc {
61
62     public static final String JavaDoc module = ControlServlet.class.getName();
63
64     public ControlServlet() {
65         super();
66     }
67
68     /**
69      * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)
70      */

71     public void init(ServletConfig JavaDoc config) throws ServletException JavaDoc {
72         super.init(config);
73         if (Debug.infoOn()) {
74             Debug.logInfo("[ControlServlet.init] Loading Control Servlet mounted on path " + config.getServletContext().getRealPath("/"), module);
75         }
76
77         // configure custom BSF engines
78
configureBsf();
79         // initialize the request handler
80
getRequestHandler();
81     }
82
83     /**
84      * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
85      */

86     public void doPost(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
87         doGet(request, response);
88     }
89
90     /**
91      * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
92      */

93     public void doGet(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
94         // setup DEFAULT chararcter encoding and content type, this will be overridden in the RequestHandler for view rendering
95
String JavaDoc charset = getServletContext().getInitParameter("charset");
96         if (charset == null || charset.length() == 0) charset = request.getCharacterEncoding();
97         if (charset == null || charset.length() == 0) charset = "UTF-8";
98         Debug.logInfo("The character encoding of the request is: [" + request.getCharacterEncoding() + "]. The character encoding we will use for the request and response is: [" + charset + "]", module);
99
100         if (!"none".equals(charset)) {
101             request.setCharacterEncoding(charset);
102         }
103
104         // setup content type
105
String JavaDoc contentType = "text/html";
106         if (charset.length() > 0 && !"none".equals(charset)) {
107             response.setContentType(contentType + "; charset=" + charset);
108             response.setCharacterEncoding(charset);
109         } else {
110             response.setContentType(contentType);
111         }
112
113         long requestStartTime = System.currentTimeMillis();
114         HttpSession JavaDoc session = request.getSession();
115
116         GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
117         //Debug.log("Cert Chain: " + request.getAttribute("javax.servlet.request.X509Certificate"), module);
118

119         // workaraound if we are in the root webapp
120
String JavaDoc webappName = UtilHttp.getApplicationName(request);
121
122         String JavaDoc rname = "";
123         if (request.getPathInfo() != null) {
124             rname = request.getPathInfo().substring(1);
125         }
126         if (rname.indexOf('/') > 0) {
127             rname = rname.substring(0, rname.indexOf('/'));
128         }
129
130         UtilTimer timer = null;
131         if (Debug.timingOn()) {
132             timer = new UtilTimer();
133             timer.setLog(true);
134             timer.timerString("[" + rname + "] Servlet Starting, doing setup", module);
135         }
136
137         // Setup the CONTROL_PATH for JSP dispatching.
138
request.setAttribute("_CONTROL_PATH_", request.getContextPath() + request.getServletPath());
139         if (Debug.verboseOn())
140             Debug.logVerbose("Control Path: " + request.getAttribute("_CONTROL_PATH_"), module);
141
142         // for convenience, and necessity with event handlers, make security and delegator available in the request:
143
// try to get it from the session first so that we can have a delegator/dispatcher/security for a certain user if desired
144
GenericDelegator delegator = null;
145         String JavaDoc delegatorName = (String JavaDoc) session.getAttribute("delegatorName");
146         if (UtilValidate.isNotEmpty(delegatorName)) {
147             delegator = GenericDelegator.getGenericDelegator(delegatorName);
148         }
149         if (delegator == null) {
150             delegator = (GenericDelegator) getServletContext().getAttribute("delegator");
151         }
152         if (delegator == null) {
153             Debug.logError("[ControlServlet] ERROR: delegator not found in ServletContext", module);
154         } else {
155             request.setAttribute("delegator", delegator);
156             // always put this in the session too so that session events can use the delegator
157
session.setAttribute("delegatorName", delegator.getDelegatorName());
158         }
159
160         LocalDispatcher dispatcher = (LocalDispatcher) session.getAttribute("dispatcher");
161         if (dispatcher == null) {
162             dispatcher = (LocalDispatcher) getServletContext().getAttribute("dispatcher");
163         }
164         if (dispatcher == null) {
165             Debug.logError("[ControlServlet] ERROR: dispatcher not found in ServletContext", module);
166         }
167         request.setAttribute("dispatcher", dispatcher);
168
169         Security security = (Security) session.getAttribute("security");
170         if (security == null) {
171             security = (Security) getServletContext().getAttribute("security");
172         }
173         if (security == null) {
174             Debug.logError("[ControlServlet] ERROR: security not found in ServletContext", module);
175         }
176         request.setAttribute("security", security);
177
178         // display details on the servlet objects
179
if (Debug.verboseOn()) {
180             logRequestInfo(request);
181         }
182
183         if (Debug.timingOn()) timer.timerString("[" + rname + "] Setup done, doing Event(s) and View(s)", module);
184
185         // some containers call filters on EVERY request, even forwarded ones, so let it know that it came from the control servlet
186
request.setAttribute(ContextFilter.FORWARDED_FROM_SERVLET, new Boolean JavaDoc(true));
187
188         String JavaDoc errorPage = null;
189         try {
190             // the ServerHitBin call for the event is done inside the doRequest method
191
getRequestHandler().doRequest(request, response, null, userLogin, delegator);
192         } catch (RequestHandlerException e) {
193             Throwable JavaDoc throwable = e.getNested() != null ? e.getNested() : e;
194             Debug.logError(throwable, "Error in request handler: ", module);
195             request.setAttribute("_ERROR_MESSAGE_", throwable.toString());
196             errorPage = getRequestHandler().getDefaultErrorPage(request);
197         } catch (Exception JavaDoc e) {
198             Debug.logError(e, "Error in request handler: ", module);
199             request.setAttribute("_ERROR_MESSAGE_", e.toString());
200             errorPage = getRequestHandler().getDefaultErrorPage(request);
201         }
202
203         // Forward to the JSP
204
// if (Debug.infoOn()) Debug.logInfo("[" + rname + "] Event done, rendering page: " + nextPage, module);
205
// if (Debug.timingOn()) timer.timerString("[" + rname + "] Event done, rendering page: " + nextPage, module);
206

207         if (errorPage != null) {
208             Debug.logError("An error occurred, going to the errorPage: " + errorPage, module);
209
210             RequestDispatcher JavaDoc rd = request.getRequestDispatcher(errorPage);
211
212             // use this request parameter to avoid infinite looping on errors in the error page...
213
if (request.getAttribute("_ERROR_OCCURRED_") == null && rd != null) {
214                 request.setAttribute("_ERROR_OCCURRED_", new Boolean JavaDoc(true));
215                 Debug.logError("Including errorPage: " + errorPage, module);
216                 rd.include(request, response);
217
218                 /* For some reason (with Tomcat only?) this isn't making it to the browser, and neither is the rd.include...
219                 String errorMessage = "<html><body>ERROR in error page, (infinite loop or error page not found with name [" + errorPage + "]), but here is the text just in case it helps you: " + request.getAttribute("ERROR_MESSAGE_") + "</body></html>";
220                 if (UtilJ2eeCompat.useOutputStreamNotWriter(getServletContext())) {
221                     response.getOutputStream().print(errorMessage);
222                 } else {
223                     response.getWriter().print(errorMessage);
224                 }
225                 */

226             } else {
227                 if (rd == null) {
228                     Debug.logError("Could not get RequestDispatcher for errorPage: " + errorPage, module);
229                 }
230
231                 String JavaDoc errorMessage = "<html><body>ERROR in error page, (infinite loop or error page not found with name [" + errorPage + "]), but here is the text just in case it helps you: " + request.getAttribute("ERROR_MESSAGE_") + "</body></html>";
232                 if (UtilJ2eeCompat.useOutputStreamNotWriter(getServletContext())) {
233                     response.getOutputStream().print(errorMessage);
234                 } else {
235                     response.getWriter().print(errorMessage);
236                 }
237             }
238         }
239
240         // sanity check; make sure we don't have any transactions in place
241
try {
242             // roll back current TX first
243
if (TransactionUtil.isTransactionInPlace()) {
244                 Debug.logWarning("*** NOTICE: ControlServlet finished w/ a transaction in place! Rolling back.", module);
245                 TransactionUtil.rollback();
246             }
247
248             // now resume/rollback any suspended txs
249
if (TransactionUtil.suspendedTransactionsHeld()) {
250                 int suspended = TransactionUtil.cleanSuspendedTransactions();
251                 Debug.logWarning("Resumed/Rolled Back [" + suspended + "] transactions.", module);
252             }
253         } catch (GenericTransactionException e) {
254             Debug.logWarning(e, module);
255         }
256
257         ServerHitBin.countRequest(webappName + "." + rname, request, requestStartTime, System.currentTimeMillis() - requestStartTime, userLogin, delegator);
258         if (Debug.timingOn()) timer.timerString("[" + rname + "] Done rendering page, Servlet Finished", module);
259     }
260
261     /**
262      * @see javax.servlet.Servlet#destroy()
263      */

264     public void destroy() {
265         super.destroy();
266     }
267
268     protected RequestHandler getRequestHandler() {
269         return RequestHandler.getRequestHandler(getServletContext());
270     }
271
272     protected void configureBsf() {
273         String JavaDoc[] bshExtensions = {"bsh"};
274         BSFManager.registerScriptingEngine("beanshell", "org.ofbiz.base.util.OfbizBshBsfEngine", bshExtensions);
275
276         String JavaDoc[] jsExtensions = {"js"};
277         BSFManager.registerScriptingEngine("javascript", "org.ofbiz.base.util.OfbizJsBsfEngine", jsExtensions);
278
279         String JavaDoc[] smExtensions = {"sm"};
280         BSFManager.registerScriptingEngine("simplemethod", "org.ofbiz.minilang.SimpleMethodBsfEngine", smExtensions);
281     }
282
283     protected void logRequestInfo(HttpServletRequest JavaDoc request) {
284         ServletContext JavaDoc servletContext = this.getServletContext();
285         HttpSession JavaDoc session = request.getSession();
286
287         Debug.logVerbose("--- Start Request Headers: ---", module);
288         Enumeration JavaDoc headerNames = request.getHeaderNames();
289         while (headerNames.hasMoreElements()) {
290             String JavaDoc headerName = (String JavaDoc) headerNames.nextElement();
291             Debug.logVerbose(headerName + ":" + request.getHeader(headerName), module);
292         }
293         Debug.logVerbose("--- End Request Headers: ---", module);
294
295         Debug.logVerbose("--- Start Request Parameters: ---", module);
296         Enumeration JavaDoc paramNames = request.getParameterNames();
297         while (paramNames.hasMoreElements()) {
298             String JavaDoc paramName = (String JavaDoc) paramNames.nextElement();
299             Debug.logVerbose(paramName + ":" + request.getParameter(paramName), module);
300         }
301         Debug.logVerbose("--- End Request Parameters: ---", module);
302
303         Debug.logVerbose("--- Start Request Attributes: ---", module);
304         Enumeration JavaDoc reqNames = request.getAttributeNames();
305         while (reqNames != null && reqNames.hasMoreElements()) {
306             String JavaDoc attName = (String JavaDoc) reqNames.nextElement();
307             Debug.logVerbose(attName + ":" + request.getAttribute(attName), module);
308         }
309         Debug.logVerbose("--- End Request Attributes ---", module);
310
311         Debug.logVerbose("--- Start Session Attributes: ---", module);
312         Enumeration JavaDoc sesNames = null;
313         try {
314             sesNames = session.getAttributeNames();
315         } catch (IllegalStateException JavaDoc e) {
316             Debug.logVerbose("Cannot get session attributes : " + e.getMessage(), module);
317         }
318         while (sesNames != null && sesNames.hasMoreElements()) {
319             String JavaDoc attName = (String JavaDoc) sesNames.nextElement();
320             Debug.logVerbose(attName + ":" + session.getAttribute(attName), module);
321         }
322         Debug.logVerbose("--- End Session Attributes ---", module);
323
324         Enumeration JavaDoc appNames = servletContext.getAttributeNames();
325         Debug.logVerbose("--- Start ServletContext Attributes: ---", module);
326         while (appNames != null && appNames.hasMoreElements()) {
327             String JavaDoc attName = (String JavaDoc) appNames.nextElement();
328             Debug.logVerbose(attName + ":" + servletContext.getAttribute(attName), module);
329         }
330         Debug.logVerbose("--- End ServletContext Attributes ---", module);
331     }
332 }
333
Popular Tags