KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * $Id: RequestHandler.java 6954 2006-03-09 02:28:33Z jonesde $
3  *
4  * Copyright (c) 2001-2005 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.io.Serializable JavaDoc;
29 import java.io.UnsupportedEncodingException JavaDoc;
30 import java.util.Collection JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.List JavaDoc;
33 import java.util.Locale JavaDoc;
34 import java.util.Map JavaDoc;
35 import javax.servlet.ServletContext JavaDoc;
36 import javax.servlet.http.HttpServletRequest JavaDoc;
37 import javax.servlet.http.HttpServletResponse JavaDoc;
38 import javax.servlet.http.HttpSession JavaDoc;
39
40 import javolution.util.FastMap;
41
42 import org.ofbiz.base.util.Debug;
43 import org.ofbiz.base.util.StringUtil;
44 import org.ofbiz.base.util.UtilHttp;
45 import org.ofbiz.base.util.UtilMisc;
46 import org.ofbiz.base.util.UtilObject;
47 import org.ofbiz.base.util.UtilProperties;
48 import org.ofbiz.base.util.UtilValidate;
49 import org.ofbiz.entity.GenericDelegator;
50 import org.ofbiz.entity.GenericEntityException;
51 import org.ofbiz.entity.GenericValue;
52 import org.ofbiz.webapp.event.EventFactory;
53 import org.ofbiz.webapp.event.EventHandler;
54 import org.ofbiz.webapp.event.EventHandlerException;
55 import org.ofbiz.webapp.stats.ServerHitBin;
56 import org.ofbiz.webapp.stats.VisitHandler;
57 import org.ofbiz.webapp.view.ViewFactory;
58 import org.ofbiz.webapp.view.ViewHandler;
59 import org.ofbiz.webapp.view.ViewHandlerException;
60 import org.ofbiz.webapp.website.WebSiteWorker;
61
62 /**
63  * RequestHandler - Request Processor Object
64  *
65  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
66  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
67  * @author Dustin Caldwell
68  * @version $Rev: 6954 $
69  * @since 2.0
70  */

71 public class RequestHandler implements Serializable JavaDoc {
72
73     public static final String JavaDoc module = RequestHandler.class.getName();
74     public static final String JavaDoc err_resource = "WebappUiLabels";
75
76     public static RequestHandler getRequestHandler(ServletContext JavaDoc servletContext) {
77         RequestHandler rh = (RequestHandler) servletContext.getAttribute("_REQUEST_HANDLER_");
78         if (rh == null) {
79             rh = new RequestHandler();
80             rh.init(servletContext);
81             servletContext.setAttribute("_REQUEST_HANDLER_", rh);
82         }
83         return rh;
84     }
85
86     private ServletContext JavaDoc context = null;
87     private RequestManager requestManager = null;
88     private ViewFactory viewFactory = null;
89     private EventFactory eventFactory = null;
90
91     public void init(ServletContext JavaDoc context) {
92         Debug.logInfo("[RequestHandler Loading...]", module);
93         this.context = context;
94         this.requestManager = new RequestManager(context);
95         this.viewFactory = new ViewFactory(this);
96         this.eventFactory = new EventFactory(this);
97     }
98
99     public void doRequest(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, String JavaDoc chain,
100                           GenericValue userLogin, GenericDelegator delegator) throws RequestHandlerException {
101
102         String JavaDoc eventType = null;
103         String JavaDoc eventPath = null;
104         String JavaDoc eventMethod = null;
105
106         // workaraound if we are in the root webapp
107
String JavaDoc cname = UtilHttp.getApplicationName(request);
108
109         // Grab data from request object to process
110
String JavaDoc requestUri = RequestHandler.getRequestUri(request.getPathInfo());
111         String JavaDoc nextView = RequestHandler.getNextPageUri(request.getPathInfo());
112         if (request.getAttribute("targetRequestUri") == null) {
113             if (request.getSession().getAttribute("_PREVIOUS_REQUEST_") != null) {
114                 request.setAttribute("targetRequestUri", request.getSession().getAttribute("_PREVIOUS_REQUEST_"));
115             } else {
116                 request.setAttribute("targetRequestUri", "/" + requestUri);
117             }
118         }
119
120         // Check for chained request.
121
if (chain != null) {
122             requestUri = RequestHandler.getRequestUri(chain);
123             if (request.getAttribute("_POST_CHAIN_VIEW_") != null) {
124                 nextView = (String JavaDoc) request.getAttribute("_POST_CHAIN_VIEW_");
125             } else {
126                 nextView = RequestHandler.getNextPageUri(chain);
127             }
128             if (Debug.infoOn()) Debug.logInfo("[RequestHandler]: Chain in place: requestUri=" + requestUri + " nextView=" + nextView, module);
129         } else {
130             // Check to make sure we are allowed to access this request directly. (Also checks if this request is defined.)
131
if (!requestManager.allowDirectRequest(requestUri)) {
132                 throw new RequestHandlerException("Unknown request [" + requestUri + "]; this request does not exist or cannot be called directly.");
133             }
134
135             // Check if we SHOULD be secure and are not. If we are posting let it pass to not lose data. (too late now anyway)
136
if (!request.isSecure() && requestManager.requiresHttps(requestUri) && !request.getMethod().equalsIgnoreCase("POST")) {
137                 StringBuffer JavaDoc urlBuf = new StringBuffer JavaDoc();
138                 urlBuf.append(request.getPathInfo());
139                 if (request.getQueryString() != null) {
140                     urlBuf.append("?").append(request.getQueryString());
141                 }
142                 String JavaDoc newUrl = RequestHandler.makeUrl(request, response, urlBuf.toString());
143                 if (newUrl.toUpperCase().startsWith("HTTPS")) {
144                     // if we are supposed to be secure, redirect secure.
145
callRedirect(newUrl.toString(), response, request);
146                 }
147             }
148
149             // If its the first visit run the first visit events.
150
HttpSession JavaDoc session = request.getSession();
151
152             if (session.getAttribute("visit") == null) {
153                 Debug.logInfo("This is the first request in this visit.", module);
154                 // This isn't an event because it is required to run. We do not want to make it optional.
155
VisitHandler.setInitialVisit(request, response);
156                 Collection JavaDoc events = requestManager.getFirstVisitEvents();
157
158                 if (events != null) {
159                     Iterator JavaDoc i = events.iterator();
160
161                     while (i.hasNext()) {
162                         Map JavaDoc eventMap = (Map JavaDoc) i.next();
163                         String JavaDoc eType = (String JavaDoc) eventMap.get(ConfigXMLReader.EVENT_TYPE);
164                         String JavaDoc ePath = (String JavaDoc) eventMap.get(ConfigXMLReader.EVENT_PATH);
165                         String JavaDoc eMeth = (String JavaDoc) eventMap.get(ConfigXMLReader.EVENT_METHOD);
166
167                         try {
168                             String JavaDoc returnString = this.runEvent(request, response, eType, ePath, eMeth);
169                             if (returnString != null && !returnString.equalsIgnoreCase("success")) {
170                                 throw new EventHandlerException("First-Visit event did not return 'success'.");
171                             } else if (returnString == null) {
172                                 nextView = "none:";
173                             }
174                         } catch (EventHandlerException e) {
175                             Debug.logError(e, module);
176                         }
177                     }
178                 }
179             }
180
181             // Invoke the pre-processor (but NOT in a chain)
182
Collection JavaDoc preProcEvents = requestManager.getPreProcessor();
183             if (preProcEvents != null) {
184                 Iterator JavaDoc i = preProcEvents.iterator();
185
186                 while (i.hasNext()) {
187                     Map JavaDoc eventMap = (Map JavaDoc) i.next();
188                     String JavaDoc eType = (String JavaDoc) eventMap.get(ConfigXMLReader.EVENT_TYPE);
189                     String JavaDoc ePath = (String JavaDoc) eventMap.get(ConfigXMLReader.EVENT_PATH);
190                     String JavaDoc eMeth = (String JavaDoc) eventMap.get(ConfigXMLReader.EVENT_METHOD);
191                     try {
192                         String JavaDoc returnString = this.runEvent(request, response, eType, ePath, eMeth);
193                         if (returnString != null && !returnString.equalsIgnoreCase("success")) {
194                             throw new EventHandlerException("Pre-Processor event did not return 'success'.");
195                         } else if (returnString == null) {
196                             nextView = "none:";
197                         }
198                     } catch (EventHandlerException e) {
199                         Debug.logError(e, module);
200                     }
201                 }
202             }
203         }
204
205         // Pre-Processor/First-Visit event(s) can interrupt the flow by returning null.
206
// Warning: this could cause problems if more then one event attempts to return a response.
207
if ("none:".equals(nextView)) {
208             if (Debug.infoOn()) Debug.logInfo("[Pre-Processor Interrupted Request, not running: " + requestUri, module);
209             return;
210         }
211
212         if (Debug.infoOn()) Debug.logInfo("[Processing Request]: " + requestUri, module);
213
214         String JavaDoc eventReturnString = null;
215
216         // Perform security check.
217
if (requestManager.requiresAuth(requestUri)) {
218             // Invoke the security handler
219
// catch exceptions and throw RequestHandlerException if failed.
220
Debug.logVerbose("[RequestHandler]: AuthRequired. Running security check.", module);
221             String JavaDoc checkLoginType = requestManager.getEventType("checkLogin");
222             String JavaDoc checkLoginPath = requestManager.getEventPath("checkLogin");
223             String JavaDoc checkLoginMethod = requestManager.getEventMethod("checkLogin");
224             String JavaDoc checkLoginReturnString = null;
225
226             try {
227                 checkLoginReturnString = this.runEvent(request, response, checkLoginType,
228                         checkLoginPath, checkLoginMethod);
229             } catch (EventHandlerException e) {
230                 throw new RequestHandlerException(e.getMessage(), e);
231             }
232             if (!"success".equalsIgnoreCase(checkLoginReturnString)) {
233                 // previous URL already saved by event, so just do as the return says...
234
eventReturnString = checkLoginReturnString;
235                 eventType = checkLoginType;
236                 eventPath = checkLoginPath;
237                 eventMethod = checkLoginMethod;
238                 requestUri = "checkLogin";
239             }
240         }
241
242         // Invoke the defined event (unless login failed)
243
if (eventReturnString == null) {
244             eventType = requestManager.getEventType(requestUri);
245             eventPath = requestManager.getEventPath(requestUri);
246             eventMethod = requestManager.getEventMethod(requestUri);
247             if (eventType != null && eventPath != null && eventMethod != null) {
248                 try {
249                     long eventStartTime = System.currentTimeMillis();
250
251                     // run the event
252
eventReturnString = this.runEvent(request, response, eventType, eventPath, eventMethod);
253
254                     // save the server hit
255
ServerHitBin.countEvent(cname + "." + eventMethod, request, eventStartTime,
256                             System.currentTimeMillis() - eventStartTime, userLogin, delegator);
257
258                     // set the default event return
259
if (eventReturnString == null) {
260                         nextView = "none:";
261                     }
262                 } catch (EventHandlerException e) {
263                     // check to see if there is an "error" response, if so go there and make an request error message
264
String JavaDoc tryErrorMsg = requestManager.getRequestAttribute(requestUri, "error");
265
266                     if (tryErrorMsg != null) {
267                         eventReturnString = "error";
268                         Locale JavaDoc locale = UtilHttp.getLocale(request);
269                         String JavaDoc errMsg = UtilProperties.getMessage(RequestHandler.err_resource, "requestHandler.error_call_event", locale);
270                         request.setAttribute("_ERROR_MESSAGE_", errMsg + ": " + e.toString());
271                     } else {
272                         throw new RequestHandlerException("Error calling event and no error repsonse was specified", e);
273                     }
274                 }
275             }
276         }
277
278          // If error, then display more error messages:
279
if ("error".equals(eventReturnString)) {
280              if (Debug.errorOn()) {
281                  String JavaDoc errorMessageHeader = "Request " + requestUri + " caused an error with the following message: ";
282                  if (request.getAttribute("_ERROR_MESSAGE_") != null) {
283                      Debug.logError(errorMessageHeader + request.getAttribute("_ERROR_MESSAGE_"), module);
284                  }
285                  if (request.getAttribute("_ERROR_MESSAGE_LIST_") != null) {
286                      Debug.logError(errorMessageHeader + request.getAttribute("_ERROR_MESSAGE_LIST_"), module);
287                  }
288              }
289          }
290
291         // Process the eventReturn.
292
String JavaDoc eventReturn = requestManager.getRequestAttribute(requestUri, eventReturnString);
293         if (Debug.verboseOn()) Debug.logVerbose("[Response Qualified]: " + eventReturn, module);
294
295         // Set the next view (don't use event return if success, default to nextView (which is set to eventReturn later if null); also even if success if it is a type "none" response ignore the nextView, ie use the eventReturn)
296
if (eventReturn != null && (!"success".equals(eventReturnString) || eventReturn.startsWith("none:"))) nextView = eventReturn;
297         if (Debug.verboseOn()) Debug.logVerbose("[Event Response Mapping]: " + nextView, module);
298
299         // get the previous request info
300
String JavaDoc previousRequest = (String JavaDoc) request.getSession().getAttribute("_PREVIOUS_REQUEST_");
301         String JavaDoc loginPass = (String JavaDoc) request.getAttribute("_LOGIN_PASSED_");
302
303         // restore previous redirected request's attribute, so redirected page can display previous request's error msg etc.
304
String JavaDoc preReqAttStr = (String JavaDoc) request.getSession().getAttribute("_REQ_ATTR_MAP_");
305         Map JavaDoc preRequestMap = null;
306         if(preReqAttStr!=null){
307             request.getSession().removeAttribute("_REQ_ATTR_MAP_");
308             byte [] reqAttrMapBytes = StringUtil.fromHexString(preReqAttStr);
309             preRequestMap = (java.util.Map JavaDoc)org.ofbiz.base.util.UtilObject.getObject(reqAttrMapBytes);
310             java.util.Iterator JavaDoc keys= preRequestMap.keySet().iterator();
311             while(keys.hasNext()){
312                 String JavaDoc key = (String JavaDoc) keys.next();
313                 if("_ERROR_MESSAGE_LIST_".equals(key) ||
314                         "_ERROR_MESSAGE_MAP_".equals(key) ||
315                         "_ERROR_MESSAGE_".equals(key) ||
316                         "_EVENT_MESSAGE_LIST_".equals(key) ||
317                         "_EVENT_MESSAGE_".equals(key)){
318                     Object JavaDoc value = preRequestMap.get(key);
319                     request.setAttribute(key, value);
320                }
321             }
322         }
323
324         if (Debug.verboseOn()) Debug.logVerbose("[RequestHandler]: previousRequest - " + previousRequest + " (" + loginPass + ")", module);
325
326         // if previous request exists, and a login just succeeded, do that now.
327
if (previousRequest != null && loginPass != null && loginPass.equalsIgnoreCase("TRUE")) {
328             request.getSession().removeAttribute("_PREVIOUS_REQUEST_");
329             if (Debug.infoOn()) Debug.logInfo("[Doing Previous Request]: " + previousRequest, module);
330             doRequest(request, response, previousRequest, userLogin, delegator);
331             return; // this is needed or else we will run the view twice
332
}
333
334         String JavaDoc successView = requestManager.getViewName(requestUri);
335         if ("success".equals(eventReturnString) && successView.startsWith("request:")) {
336             // chains will override any url defined views; but we will save the view for the very end
337
if (nextView != null) {
338                 request.setAttribute("_POST_CHAIN_VIEW_", nextView);
339             }
340             nextView = successView;
341         }
342
343         // Make sure we have some sort of response to go to
344
if (nextView == null) nextView = successView;
345         if (Debug.verboseOn()) Debug.logVerbose("[Current View]: " + nextView, module);
346
347         // Handle the responses - chains/views
348
if (nextView != null && nextView.startsWith("request:")) {
349             // chained request
350
Debug.logInfo("[RequestHandler.doRequest]: Response is a chained request.", module);
351             nextView = nextView.substring(8);
352             doRequest(request, response, nextView, userLogin, delegator);
353             return; // this just to be safe; not really needed
354

355         } else { // handle views
356
// first invoke the post-processor events.
357
Collection JavaDoc postProcEvents = requestManager.getPostProcessor();
358             if (postProcEvents != null) {
359                 Iterator JavaDoc i = postProcEvents.iterator();
360
361                 while (i.hasNext()) {
362                     Map JavaDoc eventMap = (Map JavaDoc) i.next();
363                     String JavaDoc eType = (String JavaDoc) eventMap.get(ConfigXMLReader.EVENT_TYPE);
364                     String JavaDoc ePath = (String JavaDoc) eventMap.get(ConfigXMLReader.EVENT_PATH);
365                     String JavaDoc eMeth = (String JavaDoc) eventMap.get(ConfigXMLReader.EVENT_METHOD);
366                     try {
367                         String JavaDoc returnString = this.runEvent(request, response, eType, ePath, eMeth);
368                         if (returnString != null && !returnString.equalsIgnoreCase("success"))
369                             throw new EventHandlerException("Post-Processor event did not return 'success'.");
370                         else if (returnString == null)
371                             nextView = "none:";
372                     } catch (EventHandlerException e) {
373                         Debug.logError(e, module);
374                     }
375                 }
376             }
377
378             if (nextView != null && nextView.startsWith("url:")) {
379                 // check for a url for redirection
380
Debug.logInfo("[RequestHandler.doRequest]: Response is a URL redirect.", module);
381                 nextView = nextView.substring(4);
382                 callRedirect(nextView, response, request);
383             } else if (nextView != null && nextView.startsWith("cross-redirect:")) {
384                 // check for a cross-application redirect
385
Debug.logInfo("[RequestHandler.doRequest]: Response is a Cross-Application redirect.", module);
386                 String JavaDoc url = nextView.startsWith("/") ? nextView : "/" + nextView;
387                 callRedirect(url + this.makeQueryString(request), response, request);
388             } else if (nextView != null && nextView.startsWith("request-redirect:")) {
389                 // check for a Request redirect
390
Debug.logInfo("[RequestHandler.doRequest]: Response is a Request redirect.", module);
391                 nextView = nextView.substring(17);
392                 callRedirect(makeLinkWithQueryString(request, response, "/" + nextView), response, request);
393             } else if (nextView != null && nextView.startsWith("request-redirect-noparam:")) {
394                 // check for a Request redirect
395
Debug.logInfo("[RequestHandler.doRequest]: Response is a Request redirect with no parameters.", module);
396                 nextView = nextView.substring(25);
397                 callRedirect(makeLink(request, response, nextView), response, request);
398             } else if (nextView != null && nextView.startsWith("view:")) {
399                 // check for a View
400
Debug.logInfo("[RequestHandler.doRequest]: Response is a view.", module);
401                 nextView = nextView.substring(5);
402                 renderView(nextView, requestManager.allowExtView(requestUri), request, response);
403             } else if (nextView != null && nextView.startsWith("none:")) {
404                 // check for a no dispatch return (meaning the return was processed by the event
405
Debug.logInfo("[RequestHandler.doRequest]: Response is handled by the event.", module);
406             } else if (nextView != null) {
407                 // a page request
408
Debug.logInfo("[RequestHandler.doRequest]: Response is a page [" + nextView + "]", module);
409                 renderView(nextView, requestManager.allowExtView(requestUri), request, response);
410             } else {
411                 // unknown request
412
throw new RequestHandlerException("Illegal response; handler could not process [" + eventReturnString + "].");
413             }
414         }
415     }
416
417     /** Find the event handler and invoke an event. */
418     public String JavaDoc runEvent(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, String JavaDoc type,
419                            String JavaDoc path, String JavaDoc method) throws EventHandlerException {
420         EventHandler eventHandler = eventFactory.getEventHandler(type);
421         return eventHandler.invoke(path, method, request, response);
422     }
423
424     /** Returns the default error page for this request. */
425     public String JavaDoc getDefaultErrorPage(HttpServletRequest JavaDoc request) {
426         //String requestUri = RequestHandler.getRequestUri(request.getPathInfo());
427
//return requestManager.getErrorPage(requestUri);
428
return requestManager.getDefaultErrorPage();
429     }
430
431     public String JavaDoc makeQueryString(HttpServletRequest JavaDoc request) {
432         Map JavaDoc paramMap = UtilHttp.getParameterMap(request);
433         StringBuffer JavaDoc queryString = new StringBuffer JavaDoc();
434         if (paramMap != null && paramMap.size() > 0) {
435             queryString.append("?");
436             Iterator JavaDoc i = paramMap.keySet().iterator();
437             while (i.hasNext()) {
438                 String JavaDoc name = (String JavaDoc) i.next();
439                 Object JavaDoc value = paramMap.get(name);
440                 if (value instanceof String JavaDoc) {
441                     if (queryString.length() > 1) {
442                         queryString.append("&");
443                     }
444                     queryString.append(name);
445                     queryString.append("=");
446                     queryString.append(value);
447                 }
448             }
449         }
450         return queryString.toString();
451     }
452
453     /** Returns the RequestManager Object. */
454     public RequestManager getRequestManager() {
455         return requestManager;
456     }
457
458     /** Returns the ServletContext Object. */
459     public ServletContext JavaDoc getServletContext() {
460         return context;
461     }
462
463     /** Returns the ViewFactory Object. */
464     public ViewFactory getViewFactory() {
465         return viewFactory;
466     }
467
468     /** Returns the EventFactory Object. */
469     public EventFactory getEventFactory() {
470         return eventFactory;
471     }
472
473     public static String JavaDoc getRequestUri(String JavaDoc path) {
474         List JavaDoc pathInfo = StringUtil.split(path, "/");
475         if (pathInfo == null || pathInfo.size() == 0) {
476             Debug.logWarning("Got nothing when splitting URI: " + path, module);
477             return null;
478         }
479         if (((String JavaDoc)pathInfo.get(0)).indexOf('?') > -1) {
480             return ((String JavaDoc) pathInfo.get(0)).substring(0, ((String JavaDoc)pathInfo.get(0)).indexOf('?'));
481         } else {
482             return (String JavaDoc) pathInfo.get(0);
483         }
484     }
485
486     public static String JavaDoc getNextPageUri(String JavaDoc path) {
487         List JavaDoc pathInfo = StringUtil.split(path, "/");
488         String JavaDoc nextPage = null;
489         if (pathInfo == null) {
490             return nextPage;
491         }
492
493         for (int i = 1; i < pathInfo.size(); i++) {
494             String JavaDoc element = (String JavaDoc) pathInfo.get(i);
495             if (element.indexOf('~') != 0) {
496                 if (element.indexOf('?') > -1) {
497                     element = element.substring(0, element.indexOf('?'));
498                 }
499                 if (i == 1) {
500                     nextPage = element;
501                 } else {
502                     nextPage = nextPage + "/" + element;
503                 }
504             }
505         }
506         return nextPage;
507     }
508
509     private void callRedirect(String JavaDoc url, HttpServletResponse JavaDoc resp, HttpServletRequest JavaDoc req) throws RequestHandlerException {
510         if (Debug.infoOn()) Debug.logInfo("[Sending redirect]: " + url, module);
511         // set the attributes in the session so we can access it.
512
java.util.Enumeration JavaDoc attributeNameEnum = req.getAttributeNames();
513         Map JavaDoc reqAttrMap = FastMap.newInstance();
514         while (attributeNameEnum.hasMoreElements()) {
515             String JavaDoc name = (String JavaDoc) attributeNameEnum.nextElement();
516             Object JavaDoc obj = req.getAttribute(name);
517             if (obj instanceof Serializable JavaDoc) {
518                 reqAttrMap.put(name, obj);
519             }
520         }
521         if (reqAttrMap.size() > 0) {
522             byte[] reqAttrMapBytes = UtilObject.getBytes(reqAttrMap);
523             if (reqAttrMapBytes != null) {
524                 req.getSession().setAttribute("_REQ_ATTR_MAP_", StringUtil.toHexString(reqAttrMapBytes));
525             }
526         }
527
528         // send the redirect
529
try {
530             resp.sendRedirect(url);
531         } catch (IOException JavaDoc ioe) {
532             throw new RequestHandlerException(ioe.getMessage(), ioe);
533         } catch (IllegalStateException JavaDoc ise) {
534             throw new RequestHandlerException(ise.getMessage(), ise);
535         }
536     }
537
538     private void renderView(String JavaDoc view, boolean allowExtView, HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc resp) throws RequestHandlerException {
539         GenericValue userLogin = (GenericValue) req.getSession().getAttribute("userLogin");
540         GenericDelegator delegator = (GenericDelegator) req.getAttribute("delegator");
541         // workaraound if we are in the root webapp
542
String JavaDoc cname = UtilHttp.getApplicationName(req);
543         String JavaDoc oldView = view;
544
545         if (view != null && view.length() > 0 && view.charAt(0) == '/') view = view.substring(1);
546
547         // if the view name starts with the control servlet name and a /, then it was an
548
// attempt to override the default view with a call back into the control servlet,
549
// so just get the target view name and use that
550
String JavaDoc servletName = req.getServletPath().substring(1);
551
552         Debug.logInfo("servletName=" + servletName + ", view=" + view, module);
553         if (view.startsWith(servletName + "/")) {
554             view = view.substring(servletName.length() + 1);
555             Debug.logInfo("a manual control servlet request was received, removing control servlet path resulting in: view=" + view, module);
556         }
557
558         if (Debug.verboseOn()) Debug.logVerbose("[Getting View Map]: " + view, module);
559
560         // before mapping the view, set a session attribute so we know where we are
561
req.setAttribute("_CURRENT_VIEW_", view);
562
563         String JavaDoc viewType = requestManager.getViewType(view);
564         String JavaDoc tempView = requestManager.getViewPage(view);
565         String JavaDoc nextPage = null;
566
567         if (tempView == null) {
568             if (!allowExtView) {
569                 throw new RequestHandlerException("No view to render.");
570             } else {
571                 nextPage = "/" + oldView;
572             }
573         } else {
574             nextPage = tempView;
575         }
576
577         if (Debug.verboseOn()) Debug.logVerbose("[Mapped To]: " + nextPage, module);
578
579         long viewStartTime = System.currentTimeMillis();
580
581         // setup chararcter encoding and content type
582
String JavaDoc charset = getServletContext().getInitParameter("charset");
583
584         if (charset == null || charset.length() == 0) charset = req.getCharacterEncoding();
585         if (charset == null || charset.length() == 0) charset = "UTF-8";
586
587         String JavaDoc viewCharset = requestManager.getViewEncoding(view);
588         //NOTE: if the viewCharset is "none" then no charset will be used
589
if (viewCharset != null && viewCharset.length() > 0) charset = viewCharset;
590
591         if (!"none".equals(charset)) {
592             try {
593                 req.setCharacterEncoding(charset);
594             } catch (UnsupportedEncodingException JavaDoc e) {
595                 throw new RequestHandlerException("Could not set character encoding to " + charset, e);
596             } catch (IllegalStateException JavaDoc e) {
597                 Debug.logInfo(e, "Could not set character encoding to " + charset + ", something has probably already committed the stream", module);
598             }
599         }
600
601         // setup content type
602
String JavaDoc contentType = "text/html";
603         String JavaDoc viewContentType = requestManager.getViewContentType(view);
604         if (viewContentType != null && viewContentType.length() > 0) contentType = viewContentType;
605
606         if (charset.length() > 0 && !"none".equals(charset)) {
607             resp.setContentType(contentType + "; charset=" + charset);
608         } else {
609             resp.setContentType(contentType);
610         }
611
612         if (Debug.verboseOn()) Debug.logVerbose("The ContentType for the " + view + " view is: " + contentType, module);
613
614         try {
615             if (Debug.verboseOn()) Debug.logVerbose("Rendering view [" + nextPage + "] of type [" + viewType + "]", module);
616             ViewHandler vh = viewFactory.getViewHandler(viewType);
617             vh.render(view, nextPage, requestManager.getViewInfo(view), contentType, charset, req, resp);
618         } catch (ViewHandlerException e) {
619             Throwable JavaDoc throwable = e.getNested() != null ? e.getNested() : e;
620
621             throw new RequestHandlerException(e.getNonNestedMessage(), throwable);
622         }
623
624         // before getting the view generation time flush the response output to get more consistent results
625
try {
626             resp.flushBuffer();
627         } catch (java.io.IOException JavaDoc e) {
628             throw new RequestHandlerException("Error flushing response buffer", e);
629         }
630
631         String JavaDoc vname = (String JavaDoc) req.getAttribute("_CURRENT_VIEW_");
632
633         if (vname != null) {
634             ServerHitBin.countView(cname + "." + vname, req, viewStartTime,
635                 System.currentTimeMillis() - viewStartTime, userLogin, delegator);
636         }
637     }
638
639     public static String JavaDoc getDefaultServerRootUrl(HttpServletRequest JavaDoc request, boolean secure) {
640         String JavaDoc httpsPort = UtilProperties.getPropertyValue("url.properties", "port.https", "443");
641         String JavaDoc httpsServer = UtilProperties.getPropertyValue("url.properties", "force.https.host");
642         String JavaDoc httpPort = UtilProperties.getPropertyValue("url.properties", "port.http", "80");
643         String JavaDoc httpServer = UtilProperties.getPropertyValue("url.properties", "force.http.host");
644         boolean useHttps = UtilProperties.propertyValueEqualsIgnoreCase("url.properties", "port.https.enabled", "Y");
645
646         StringBuffer JavaDoc newURL = new StringBuffer JavaDoc();
647
648         if (secure && useHttps) {
649             String JavaDoc server = httpsServer;
650             if (server == null || server.length() == 0) {
651                 server = request.getServerName();
652             }
653
654             newURL.append("https://");
655             newURL.append(server);
656             if (!httpsPort.equals("443")) {
657                 newURL.append(":").append(httpsPort);
658             }
659
660         } else {
661             String JavaDoc server = httpServer;
662             if (server == null || server.length() == 0) {
663                 server = request.getServerName();
664             }
665
666             newURL.append("http://");
667             newURL.append(server);
668             if (!httpPort.equals("80")) {
669                 newURL.append(":").append(httpPort);
670             }
671         }
672         return newURL.toString();
673     }
674
675
676     public String JavaDoc makeLinkWithQueryString(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, String JavaDoc url) {
677         String JavaDoc initialLink = this.makeLink(request, response, url);
678         String JavaDoc queryString = this.makeQueryString(request);
679         return initialLink + queryString;
680     }
681
682     public String JavaDoc makeLink(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, String JavaDoc url) {
683         return makeLink(request, response, url, false, false, true);
684     }
685
686     public String JavaDoc makeLink(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, String JavaDoc url, boolean fullPath, boolean secure, boolean encode) {
687         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
688         String JavaDoc webSiteId = WebSiteWorker.getWebSiteId(request);
689
690         String JavaDoc httpsPort = null;
691         String JavaDoc httpsServer = null;
692         String JavaDoc httpPort = null;
693         String JavaDoc httpServer = null;
694         Boolean JavaDoc enableHttps = null;
695
696         // load the properties from the website entity
697
GenericValue webSite = null;
698         if (webSiteId != null) {
699             try {
700                 webSite = delegator.findByPrimaryKeyCache("WebSite", UtilMisc.toMap("webSiteId", webSiteId));
701                 if (webSite != null) {
702                     httpsPort = webSite.getString("httpsPort");
703                     httpsServer = webSite.getString("httpsHost");
704                     httpPort = webSite.getString("httpPort");
705                     httpServer = webSite.getString("httpHost");
706                     enableHttps = webSite.getBoolean("enableHttps");
707                 }
708             } catch (GenericEntityException e) {
709                 Debug.logWarning(e, "Problems with WebSite entity; using global defaults", module);
710             }
711         }
712
713         // fill in any missing properties with fields from the global file
714
if (UtilValidate.isEmpty(httpsPort)) {
715             httpsPort = UtilProperties.getPropertyValue("url.properties", "port.https", "443");
716         }
717         if (UtilValidate.isEmpty(httpServer)) {
718             httpsServer = UtilProperties.getPropertyValue("url.properties", "force.https.host");
719         }
720         if (UtilValidate.isEmpty(httpPort)) {
721             httpPort = UtilProperties.getPropertyValue("url.properties", "port.http", "80");
722         }
723         if (UtilValidate.isEmpty(httpServer)) {
724             httpServer = UtilProperties.getPropertyValue("url.properties", "force.http.host");
725         }
726         if (enableHttps == null) {
727             enableHttps = new Boolean JavaDoc(UtilProperties.propertyValueEqualsIgnoreCase("url.properties", "port.https.enabled", "Y"));
728         }
729
730         // create the path the the control servlet
731
String JavaDoc controlPath = (String JavaDoc) request.getAttribute("_CONTROL_PATH_");
732
733         String JavaDoc requestUri = RequestHandler.getRequestUri(url);
734         StringBuffer JavaDoc newURL = new StringBuffer JavaDoc();
735
736         boolean useHttps = enableHttps.booleanValue();
737         boolean didFullSecure = false;
738         boolean didFullStandard = false;
739         if (useHttps || fullPath || secure) {
740             if (secure || (useHttps && requestManager.requiresHttps(requestUri) && !request.isSecure())) {
741                 String JavaDoc server = httpsServer;
742                 if (server == null || server.length() == 0) {
743                     server = request.getServerName();
744                 }
745
746                 newURL.append("https://");
747                 newURL.append(server);
748                 if (!httpsPort.equals("443")) {
749                     newURL.append(":").append(httpsPort);
750                 }
751
752                 didFullSecure = true;
753             } else if (fullPath || (useHttps && !requestManager.requiresHttps(requestUri) && request.isSecure())) {
754                 String JavaDoc server = httpServer;
755                 if (server == null || server.length() == 0) {
756                     server = request.getServerName();
757                 }
758
759                 newURL.append("http://");
760                 newURL.append(server);
761                 if (!httpPort.equals("80")) {
762                     newURL.append(":" + httpPort);
763                 }
764
765                 didFullStandard = true;
766             }
767         }
768
769         newURL.append(controlPath);
770
771         // now add the actual passed url, but if it doesn't start with a / add one first
772
if (!url.startsWith("/")) {
773             newURL.append("/");
774         }
775         newURL.append(url);
776
777         String JavaDoc encodedUrl = null;
778         if (encode) {
779             boolean forceManualJsessionid = false;
780
781             // if this isn't a secure page, but we made a secure URL, make sure we manually add the jsessionid since the response.encodeURL won't do that
782
if (!request.isSecure() && didFullSecure) {
783                 forceManualJsessionid = true;
784             }
785
786             // if this is a secure page, but we made a standard URL, make sure we manually add the jsessionid since the response.encodeURL won't do that
787
if (request.isSecure() && didFullStandard) {
788                 forceManualJsessionid = true;
789             }
790
791             if (response != null && !forceManualJsessionid) {
792                 encodedUrl = response.encodeURL(newURL.toString());
793             } else {
794                 String JavaDoc sessionId = ";jsessionid=" + request.getSession().getId();
795                 // this should be inserted just after the "?" for the parameters, if there is one, or at the end of the string
796
int questionIndex = newURL.indexOf("?");
797                 if (questionIndex == -1) {
798                     newURL.append(sessionId);
799                 } else {
800                     newURL.insert(questionIndex, sessionId);
801                 }
802                 encodedUrl = newURL.toString();
803             }
804         } else {
805             encodedUrl = newURL.toString();
806         }
807         //if (encodedUrl.indexOf("null") > 0) {
808
//Debug.logError("in makeLink, controlPath:" + controlPath + " url:" + url, "");
809
//throw new RuntimeException("in makeLink, controlPath:" + controlPath + " url:" + url);
810
//}
811

812         //Debug.logInfo("Making URL, encode=" + encode + " for URL: " + newURL + "\n encodedUrl: " + encodedUrl, module);
813

814         return encodedUrl;
815     }
816
817     public static String JavaDoc makeUrl(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, String JavaDoc url) {
818         return makeUrl(request, response, url, false, false, false);
819     }
820
821     public static String JavaDoc makeUrl(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, String JavaDoc url, boolean fullPath, boolean secure, boolean encode) {
822         ServletContext JavaDoc ctx = (ServletContext JavaDoc) request.getAttribute("servletContext");
823         RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_");
824         return rh.makeLink(request, response, url, fullPath, secure, encode);
825     }
826
827     public void runAfterLoginEvents(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
828         List JavaDoc afterLoginEvents = requestManager.getAfterLoginEventList();
829         if (afterLoginEvents != null) {
830             Iterator JavaDoc i = afterLoginEvents.iterator();
831             while (i.hasNext()) {
832                 Map JavaDoc eventMap = (Map JavaDoc) i.next();
833                 String JavaDoc eType = (String JavaDoc) eventMap.get(ConfigXMLReader.EVENT_TYPE);
834                 String JavaDoc ePath = (String JavaDoc) eventMap.get(ConfigXMLReader.EVENT_PATH);
835                 String JavaDoc eMeth = (String JavaDoc) eventMap.get(ConfigXMLReader.EVENT_METHOD);
836                 try {
837                     String JavaDoc returnString = this.runEvent(request, response, eType, ePath, eMeth);
838                     if (returnString != null && !returnString.equalsIgnoreCase("success")) {
839                         throw new EventHandlerException("Pre-Processor event did not return 'success'.");
840                     }
841                 } catch (EventHandlerException e) {
842                     Debug.logError(e, module);
843                 }
844             }
845         }
846     }
847
848     public void runBeforeLogoutEvents(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
849         List JavaDoc beforeLogoutEvents = requestManager.getBeforeLogoutEventList();
850         if (beforeLogoutEvents != null) {
851             Iterator JavaDoc i = beforeLogoutEvents.iterator();
852             while (i.hasNext()) {
853                 Map JavaDoc eventMap = (Map JavaDoc) i.next();
854                 String JavaDoc eType = (String JavaDoc) eventMap.get(ConfigXMLReader.EVENT_TYPE);
855                 String JavaDoc ePath = (String JavaDoc) eventMap.get(ConfigXMLReader.EVENT_PATH);
856                 String JavaDoc eMeth = (String JavaDoc) eventMap.get(ConfigXMLReader.EVENT_METHOD);
857                 try {
858                     String JavaDoc returnString = this.runEvent(request, response, eType, ePath, eMeth);
859                     if (returnString != null && !returnString.equalsIgnoreCase("success")) {
860                         throw new EventHandlerException("Pre-Processor event did not return 'success'.");
861                     }
862                 } catch (EventHandlerException e) {
863                     Debug.logError(e, module);
864                 }
865             }
866         }
867     }
868 }
869
Popular Tags