001: /*
002: * $Id: ControlServlet.java,v 1.5 2004/01/24 16:08:23 ajzeneski Exp $
003: *
004: * Copyright (c) 2001-2003 The Open For Business Project - www.ofbiz.org
005: *
006: * Permission is hereby granted, free of charge, to any person obtaining a
007: * copy of this software and associated documentation files (the "Software"),
008: * to deal in the Software without restriction, including without limitation
009: * the rights to use, copy, modify, merge, publish, distribute, sublicense,
010: * and/or sell copies of the Software, and to permit persons to whom the
011: * Software is furnished to do so, subject to the following conditions:
012: *
013: * The above copyright notice and this permission notice shall be included
014: * in all copies or substantial portions of the Software.
015: *
016: * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
017: * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
018: * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
019: * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
020: * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
021: * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
022: * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
023: */
024: package org.ofbiz.content.webapp.control;
025:
026: import java.io.IOException;
027: import java.util.Enumeration;
028:
029: import javax.servlet.RequestDispatcher;
030: import javax.servlet.ServletConfig;
031: import javax.servlet.ServletContext;
032: import javax.servlet.ServletException;
033: import javax.servlet.http.HttpServlet;
034: import javax.servlet.http.HttpServletRequest;
035: import javax.servlet.http.HttpServletResponse;
036: import javax.servlet.http.HttpSession;
037:
038: import org.ofbiz.base.util.Debug;
039: import org.ofbiz.base.util.UtilHttp;
040: import org.ofbiz.base.util.UtilJ2eeCompat;
041: import org.ofbiz.base.util.UtilTimer;
042: import org.ofbiz.base.util.UtilValidate;
043: import org.ofbiz.content.stats.ServerHitBin;
044: import org.ofbiz.content.webapp.view.JPublishWrapper;
045: import org.ofbiz.entity.GenericDelegator;
046: import org.ofbiz.entity.GenericValue;
047: import org.ofbiz.security.Security;
048: import org.ofbiz.service.LocalDispatcher;
049:
050: import com.ibm.bsf.BSFManager;
051:
052: /**
053: * ControlServlet.java - Master servlet for the web application.
054: *
055: * @author <a href="mailto:jaz@ofbiz.org">Andy Zeneski</a>
056: * @author <a href="mailto:jonesde@ofbiz.org">David E. Jones</a>
057: * @version $Revision: 1.5 $
058: * @since 2.0
059: */
060: public class ControlServlet extends HttpServlet {
061:
062: public static final String module = ControlServlet.class.getName();
063:
064: public ControlServlet() {
065: super ();
066: }
067:
068: /**
069: * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)
070: */
071: public void init(ServletConfig config) throws ServletException {
072: super .init(config);
073: if (Debug.infoOn()) {
074: Debug.logInfo(
075: "[ControlServlet.init] Loading Control Servlet mounted on path "
076: + config.getServletContext().getRealPath(
077: "/"), module);
078: }
079:
080: // configure custom BSF engines
081: configureBsf();
082: // initialize the request handler
083: getRequestHandler();
084: // initialize the JPublish wrapper
085: getJPublishWrapper();
086: }
087:
088: /**
089: * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
090: */
091: public void doPost(HttpServletRequest request,
092: HttpServletResponse response) throws ServletException,
093: IOException {
094: doGet(request, response);
095: }
096:
097: /**
098: * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
099: */
100: public void doGet(HttpServletRequest request,
101: HttpServletResponse response) throws ServletException,
102: IOException {
103: // setup DEFAULT chararcter encoding and content type, this will be overridden in the RequestHandler for view rendering
104: String charset = getServletContext()
105: .getInitParameter("charset");
106: if (charset == null || charset.length() == 0)
107: charset = request.getCharacterEncoding();
108: if (charset == null || charset.length() == 0)
109: charset = "UTF-8";
110: if (!"none".equals(charset)) {
111: request.setCharacterEncoding(charset);
112: }
113:
114: // setup content type
115: String contentType = "text/html";
116: if (charset.length() > 0 && !"none".equals(charset)) {
117: response.setContentType(contentType + "; charset="
118: + charset);
119: } else {
120: response.setContentType(contentType);
121: }
122:
123: long requestStartTime = System.currentTimeMillis();
124: HttpSession session = request.getSession();
125:
126: GenericValue userLogin = (GenericValue) session
127: .getAttribute("userLogin");
128: //Debug.log("Cert Chain: " + request.getAttribute("javax.servlet.request.X509Certificate"), module);
129:
130: // workaraound if we are in the root webapp
131: String webappName = UtilHttp.getApplicationName(request);
132:
133: String rname = "";
134: if (request.getPathInfo() != null) {
135: rname = request.getPathInfo().substring(1);
136: }
137: if (rname.indexOf('/') > 0) {
138: rname = rname.substring(0, rname.indexOf('/'));
139: }
140:
141: UtilTimer timer = null;
142: if (Debug.timingOn()) {
143: timer = new UtilTimer();
144: timer.setLog(true);
145: timer.timerString("[" + rname
146: + "] Servlet Starting, doing setup", module);
147: }
148:
149: // Setup the CONTROL_PATH for JSP dispatching.
150: request.setAttribute("_CONTROL_PATH_", request.getContextPath()
151: + request.getServletPath());
152: if (Debug.verboseOn())
153: Debug.logVerbose("Control Path: "
154: + request.getAttribute("_CONTROL_PATH_"), module);
155:
156: // for convenience, and necessity with event handlers, make security and delegator available in the request:
157: // try to get it from the session first so that we can have a delegator/dispatcher/security for a certain user if desired
158: GenericDelegator delegator = null;
159: String delegatorName = (String) session
160: .getAttribute("delegatorName");
161: if (UtilValidate.isNotEmpty(delegatorName)) {
162: delegator = GenericDelegator
163: .getGenericDelegator(delegatorName);
164: }
165: if (delegator == null) {
166: delegator = (GenericDelegator) getServletContext()
167: .getAttribute("delegator");
168: }
169: if (delegator == null) {
170: Debug
171: .logError(
172: "[ControlServlet] ERROR: delegator not found in ServletContext",
173: module);
174: } else {
175: request.setAttribute("delegator", delegator);
176: // always put this in the session too so that session events can use the delegator
177: session.setAttribute("delegatorName", delegator
178: .getDelegatorName());
179: }
180:
181: LocalDispatcher dispatcher = (LocalDispatcher) session
182: .getAttribute("dispatcher");
183: if (dispatcher == null) {
184: dispatcher = (LocalDispatcher) getServletContext()
185: .getAttribute("dispatcher");
186: }
187: if (dispatcher == null) {
188: Debug
189: .logError(
190: "[ControlServlet] ERROR: dispatcher not found in ServletContext",
191: module);
192: }
193: request.setAttribute("dispatcher", dispatcher);
194:
195: Security security = (Security) session.getAttribute("security");
196: if (security == null) {
197: security = (Security) getServletContext().getAttribute(
198: "security");
199: }
200: if (security == null) {
201: Debug
202: .logError(
203: "[ControlServlet] ERROR: security not found in ServletContext",
204: module);
205: }
206: request.setAttribute("security", security);
207:
208: // display details on the servlet objects
209: if (Debug.verboseOn()) {
210: logRequestInfo(request);
211: }
212:
213: if (Debug.timingOn())
214: timer.timerString("[" + rname
215: + "] Setup done, doing Event(s) and View(s)",
216: module);
217:
218: String errorPage = null;
219: try {
220: // the ServerHitBin call for the event is done inside the doRequest method
221: getRequestHandler().doRequest(request, response, null,
222: userLogin, delegator);
223: } catch (RequestHandlerException e) {
224: Throwable throwable = e.getNested() != null ? e.getNested()
225: : e;
226: Debug.logError(throwable, "Error in request handler: ",
227: module);
228: request.setAttribute("_ERROR_MESSAGE_", throwable
229: .toString());
230: errorPage = getRequestHandler()
231: .getDefaultErrorPage(request);
232: } catch (Exception e) {
233: Debug.logError(e, "Error in request handler: ", module);
234: request.setAttribute("_ERROR_MESSAGE_", e.toString());
235: errorPage = getRequestHandler()
236: .getDefaultErrorPage(request);
237: }
238:
239: // Forward to the JSP
240: // if (Debug.infoOn()) Debug.logInfo("[" + rname + "] Event done, rendering page: " + nextPage, module);
241: // if (Debug.timingOn()) timer.timerString("[" + rname + "] Event done, rendering page: " + nextPage, module);
242:
243: if (errorPage != null) {
244: Debug.logError(
245: "An error occurred, going to the errorPage: "
246: + errorPage, module);
247:
248: // some containers call filters on EVERY request, even forwarded ones, so let it know that it came from the control servlet
249: request.setAttribute(ContextFilter.FORWARDED_FROM_SERVLET,
250: new Boolean(true));
251: RequestDispatcher rd = request
252: .getRequestDispatcher(errorPage);
253:
254: // use this request parameter to avoid infinite looping on errors in the error page...
255: if (request.getAttribute("_ERROR_OCCURRED_") == null
256: && rd != null) {
257: request.setAttribute("_ERROR_OCCURRED_", new Boolean(
258: true));
259: rd.include(request, response);
260: } else {
261: String errorMessage = "ERROR in error page, (infinite loop or error page not found with name ["
262: + errorPage
263: + "]), but here is the text just in case it helps you: "
264: + request.getAttribute("ERROR_MESSAGE_");
265:
266: if (UtilJ2eeCompat
267: .useOutputStreamNotWriter(getServletContext())) {
268: response.getOutputStream().print(errorMessage);
269: } else {
270: response.getWriter().print(errorMessage);
271: }
272: }
273: }
274:
275: ServerHitBin.countRequest(webappName + "." + rname, request,
276: requestStartTime, System.currentTimeMillis()
277: - requestStartTime, userLogin, delegator);
278: if (Debug.timingOn())
279: timer
280: .timerString(
281: "["
282: + rname
283: + "] Done rendering page, Servlet Finished",
284: module);
285: }
286:
287: /**
288: * @see javax.servlet.Servlet#destroy()
289: */
290: public void destroy() {
291: super .destroy();
292: }
293:
294: protected RequestHandler getRequestHandler() {
295: RequestHandler rh = (RequestHandler) getServletContext()
296: .getAttribute("_REQUEST_HANDLER_");
297: if (rh == null) {
298: rh = new RequestHandler();
299: rh.init(getServletContext());
300: getServletContext().setAttribute("_REQUEST_HANDLER_", rh);
301: }
302: return rh;
303: }
304:
305: protected JPublishWrapper getJPublishWrapper() {
306: JPublishWrapper jp = (JPublishWrapper) getServletContext()
307: .getAttribute("jpublishWrapper");
308: if (jp == null) {
309: jp = new JPublishWrapper(getServletContext());
310: getServletContext().setAttribute("jpublishWrapper", jp);
311: }
312: return jp;
313: }
314:
315: protected void configureBsf() {
316: String[] bshExtensions = { "bsh" };
317: BSFManager.registerScriptingEngine("beanshell",
318: "org.ofbiz.base.util.OfbizBshBsfEngine", bshExtensions);
319:
320: String[] jsExtensions = { "js" };
321: BSFManager.registerScriptingEngine("javascript",
322: "org.ofbiz.base.util.OfbizJsBsfEngine", jsExtensions);
323:
324: String[] smExtensions = { "sm" };
325: BSFManager.registerScriptingEngine("simplemethod",
326: "org.ofbiz.minilang.SimpleMethodBsfEngine",
327: smExtensions);
328: }
329:
330: protected void logRequestInfo(HttpServletRequest request) {
331: ServletContext servletContext = this .getServletContext();
332: HttpSession session = request.getSession();
333:
334: Debug.logVerbose("--- Start Request Headers: ---", module);
335: Enumeration headerNames = request.getHeaderNames();
336: while (headerNames.hasMoreElements()) {
337: String headerName = (String) headerNames.nextElement();
338: Debug.logVerbose(headerName + ":"
339: + request.getHeader(headerName), module);
340: }
341: Debug.logVerbose("--- End Request Headers: ---", module);
342:
343: Debug.logVerbose("--- Start Request Parameters: ---", module);
344: Enumeration paramNames = request.getParameterNames();
345: while (paramNames.hasMoreElements()) {
346: String paramName = (String) paramNames.nextElement();
347: Debug.logVerbose(paramName + ":"
348: + request.getParameter(paramName), module);
349: }
350: Debug.logVerbose("--- End Request Parameters: ---", module);
351:
352: Debug.logVerbose("--- Start Request Attributes: ---", module);
353: Enumeration reqNames = request.getAttributeNames();
354: while (reqNames != null && reqNames.hasMoreElements()) {
355: String attName = (String) reqNames.nextElement();
356: Debug.logVerbose(attName + ":"
357: + request.getAttribute(attName), module);
358: }
359: Debug.logVerbose("--- End Request Attributes ---", module);
360:
361: Debug.logVerbose("--- Start Session Attributes: ---", module);
362: Enumeration sesNames = null;
363: try {
364: sesNames = session.getAttributeNames();
365: } catch (IllegalStateException e) {
366: Debug.logVerbose("Cannot get session attributes : "
367: + e.getMessage(), module);
368: }
369: while (sesNames != null && sesNames.hasMoreElements()) {
370: String attName = (String) sesNames.nextElement();
371: Debug.logVerbose(attName + ":"
372: + session.getAttribute(attName), module);
373: }
374: Debug.logVerbose("--- End Session Attributes ---", module);
375:
376: Enumeration appNames = servletContext.getAttributeNames();
377: Debug.logVerbose("--- Start ServletContext Attributes: ---",
378: module);
379: while (appNames != null && appNames.hasMoreElements()) {
380: String attName = (String) appNames.nextElement();
381: Debug.logVerbose(attName + ":"
382: + servletContext.getAttribute(attName), module);
383: }
384: Debug.logVerbose("--- End ServletContext Attributes ---",
385: module);
386: }
387: }
|