Source Code Cross Referenced for RequestHandler.java in  » ERP-CRM-Financial » SourceTap-CRM » org » ofbiz » content » webapp » control » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » ERP CRM Financial » SourceTap CRM » org.ofbiz.content.webapp.control 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * $Id: RequestHandler.java,v 1.10 2003/12/09 17:35:10 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:         */
025:        package org.ofbiz.content.webapp.control;
026:
027:        import java.io.IOException;
028:        import java.io.Serializable;
029:        import java.io.UnsupportedEncodingException;
030:        import java.util.Collection;
031:        import java.util.HashMap;
032:        import java.util.Iterator;
033:        import java.util.List;
034:        import java.util.Map;
035:
036:        import javax.servlet.ServletContext;
037:        import javax.servlet.http.HttpServletRequest;
038:        import javax.servlet.http.HttpServletResponse;
039:        import javax.servlet.http.HttpSession;
040:
041:        import org.ofbiz.base.util.Debug;
042:        import org.ofbiz.base.util.StringUtil;
043:        import org.ofbiz.base.util.UtilHttp;
044:        import org.ofbiz.base.util.UtilMisc;
045:        import org.ofbiz.base.util.UtilProperties;
046:        import org.ofbiz.content.stats.ServerHitBin;
047:        import org.ofbiz.content.stats.VisitHandler;
048:        import org.ofbiz.content.webapp.event.EventFactory;
049:        import org.ofbiz.content.webapp.event.EventHandler;
050:        import org.ofbiz.content.webapp.event.EventHandlerException;
051:        import org.ofbiz.content.webapp.view.ViewFactory;
052:        import org.ofbiz.content.webapp.view.ViewHandler;
053:        import org.ofbiz.content.webapp.view.ViewHandlerException;
054:        import org.ofbiz.content.website.WebSiteWorker;
055:        import org.ofbiz.entity.GenericDelegator;
056:        import org.ofbiz.entity.GenericEntityException;
057:        import org.ofbiz.entity.GenericValue;
058:
059:        /**
060:         * RequestHandler - Request Processor Object
061:         *
062:         * @author     <a href="mailto:jaz@ofbiz.org">Andy Zeneski</a>
063:         * @author     <a href="mailto:jonesde@ofbiz.org">David E. Jones</a>
064:         * @author     Dustin Caldwell
065:         * @version    $Revision: 1.10 $
066:         * @since      2.0
067:         */
068:        public class RequestHandler implements  Serializable {
069:
070:            public static final String module = RequestHandler.class.getName();
071:
072:            private ServletContext context = null;
073:            private RequestManager requestManager = null;
074:            private ViewFactory viewFactory = null;
075:            private EventFactory eventFactory = null;
076:
077:            public void init(ServletContext context) {
078:                Debug.logInfo("[RequestHandler Loading...]", module);
079:                this .context = context;
080:                this .requestManager = new RequestManager(context);
081:                this .viewFactory = new ViewFactory(this );
082:                this .eventFactory = new EventFactory(this );
083:            }
084:
085:            public void doRequest(HttpServletRequest request,
086:                    HttpServletResponse response, String chain,
087:                    GenericValue userLogin, GenericDelegator delegator)
088:                    throws RequestHandlerException {
089:
090:                String eventType = null;
091:                String eventPath = null;
092:                String eventMethod = null;
093:
094:                // workaraound if we are in the root webapp
095:                String cname = UtilHttp.getApplicationName(request);
096:
097:                // Grab data from request object to process
098:                String requestUri = RequestHandler.getRequestUri(request
099:                        .getPathInfo());
100:                String nextView = RequestHandler.getNextPageUri(request
101:                        .getPathInfo());
102:
103:                // Check for chained request.
104:                if (chain != null) {
105:                    requestUri = RequestHandler.getRequestUri(chain);
106:                    if (request.getAttribute("_POST_CHAIN_VIEW_") != null) {
107:                        nextView = (String) request
108:                                .getAttribute("_POST_CHAIN_VIEW_");
109:                    } else {
110:                        nextView = RequestHandler.getNextPageUri(chain);
111:                    }
112:                    if (Debug.infoOn())
113:                        Debug.logInfo(
114:                                "[RequestHandler]: Chain in place: requestUri="
115:                                        + requestUri + " nextView=" + nextView,
116:                                module);
117:                } else {
118:                    // Check to make sure we are allowed to access this request directly. (Also checks if this request is defined.)
119:                    if (!requestManager.allowDirectRequest(requestUri)) {
120:                        throw new RequestHandlerException(
121:                                "Unknown request ["
122:                                        + requestUri
123:                                        + "]; this request does not exist or cannot be called directly.");
124:                    }
125:
126:                    // Check if we SHOULD be secure and are not. If we are posting let it pass to not lose data. (too late now anyway)
127:                    if (!request.isSecure()
128:                            && requestManager.requiresHttps(requestUri)
129:                            && !request.getMethod().equalsIgnoreCase("POST")) {
130:                        String port = UtilProperties.getPropertyValue(
131:                                "url.properties", "port.https", "443");
132:
133:                        if (UtilProperties.propertyValueEqualsIgnoreCase(
134:                                "url.properties", "port.https.enabled", "Y")) {
135:                            StringBuffer newUrl = new StringBuffer();
136:
137:                            newUrl.append("https://");
138:                            String server = UtilProperties.getPropertyValue(
139:                                    "url.properties", "force.http.host",
140:                                    request.getServerName());
141:
142:                            newUrl.append(server);
143:                            if (!port.equals("443")) {
144:                                newUrl.append(":" + port);
145:                            }
146:                            newUrl.append((String) request
147:                                    .getAttribute("_CONTROL_PATH_"));
148:                            newUrl.append(request.getPathInfo());
149:                            if (request.getQueryString() != null)
150:                                newUrl.append("?" + request.getQueryString());
151:
152:                            // if we are supposed to be secure, redirect secure.
153:                            callRedirect(newUrl.toString(), response);
154:                        }
155:                    }
156:
157:                    // If its the first visit run the first visit events.
158:                    HttpSession session = request.getSession();
159:
160:                    if (session.getAttribute("visit") == null) {
161:                        // This isn't an event because it is required to run. We do not want to make it optional.
162:                        VisitHandler.setInitialVisit(request);
163:                        Collection events = requestManager
164:                                .getFirstVisitEvents();
165:
166:                        if (events != null) {
167:                            Iterator i = events.iterator();
168:
169:                            while (i.hasNext()) {
170:                                Map eventMap = (Map) i.next();
171:                                String eType = (String) eventMap
172:                                        .get(ConfigXMLReader.EVENT_TYPE);
173:                                String ePath = (String) eventMap
174:                                        .get(ConfigXMLReader.EVENT_PATH);
175:                                String eMeth = (String) eventMap
176:                                        .get(ConfigXMLReader.EVENT_METHOD);
177:
178:                                try {
179:                                    String returnString = this .runEvent(
180:                                            request, response, eType, ePath,
181:                                            eMeth);
182:                                    if (returnString != null
183:                                            && !returnString
184:                                                    .equalsIgnoreCase("success")) {
185:                                        throw new EventHandlerException(
186:                                                "First-Visit event did not return 'success'.");
187:                                    } else if (returnString == null) {
188:                                        nextView = "none:";
189:                                    }
190:                                } catch (EventHandlerException e) {
191:                                    Debug.logError(e, module);
192:                                }
193:                            }
194:                        }
195:                    }
196:
197:                    // Invoke the pre-processor (but NOT in a chain)
198:                    Collection preProcEvents = requestManager.getPreProcessor();
199:                    if (preProcEvents != null) {
200:                        Iterator i = preProcEvents.iterator();
201:
202:                        while (i.hasNext()) {
203:                            Map eventMap = (HashMap) i.next();
204:                            String eType = (String) eventMap
205:                                    .get(ConfigXMLReader.EVENT_TYPE);
206:                            String ePath = (String) eventMap
207:                                    .get(ConfigXMLReader.EVENT_PATH);
208:                            String eMeth = (String) eventMap
209:                                    .get(ConfigXMLReader.EVENT_METHOD);
210:                            try {
211:                                String returnString = this .runEvent(request,
212:                                        response, eType, ePath, eMeth);
213:                                if (returnString != null
214:                                        && !returnString
215:                                                .equalsIgnoreCase("success")) {
216:                                    throw new EventHandlerException(
217:                                            "Pre-Processor event did not return 'success'.");
218:                                } else if (returnString == null) {
219:                                    nextView = "none:";
220:                                }
221:                            } catch (EventHandlerException e) {
222:                                Debug.logError(e, module);
223:                            }
224:                        }
225:                    }
226:                }
227:
228:                // Pre-Processor/First-Visit event(s) can interrupt the flow by returning null.
229:                // Warning: this could cause problems if more then one event attempts to return a response.
230:                if ("none:".equals(nextView)) {
231:                    if (Debug.infoOn())
232:                        Debug.logInfo(
233:                                "[Pre-Processor Interrupted Request, not running: "
234:                                        + requestUri, module);
235:                    return;
236:                }
237:
238:                if (Debug.infoOn())
239:                    Debug
240:                            .logInfo("[Processing Request]: " + requestUri,
241:                                    module);
242:
243:                String eventReturnString = null;
244:
245:                // Perform security check.
246:                if (requestManager.requiresAuth(requestUri)) {
247:                    // Invoke the security handler
248:                    // catch exceptions and throw RequestHandlerException if failed.
249:                    Debug
250:                            .logVerbose(
251:                                    "[RequestHandler]: AuthRequired. Running security check.",
252:                                    module);
253:                    String checkLoginType = requestManager
254:                            .getEventType("checkLogin");
255:                    String checkLoginPath = requestManager
256:                            .getEventPath("checkLogin");
257:                    String checkLoginMethod = requestManager
258:                            .getEventMethod("checkLogin");
259:                    String checkLoginReturnString = null;
260:
261:                    try {
262:                        checkLoginReturnString = this .runEvent(request,
263:                                response, checkLoginType, checkLoginPath,
264:                                checkLoginMethod);
265:                    } catch (EventHandlerException e) {
266:                        throw new RequestHandlerException(e.getMessage(), e);
267:                    }
268:                    if (!"success".equalsIgnoreCase(checkLoginReturnString)) {
269:                        // previous URL already saved by event, so just do as the return says...
270:                        eventReturnString = checkLoginReturnString;
271:                        eventType = checkLoginType;
272:                        eventPath = checkLoginPath;
273:                        eventMethod = checkLoginMethod;
274:                        requestUri = "checkLogin";
275:                    }
276:                }
277:
278:                // Invoke the defined event (unless login failed)
279:                if (eventReturnString == null) {
280:                    eventType = requestManager.getEventType(requestUri);
281:                    eventPath = requestManager.getEventPath(requestUri);
282:                    eventMethod = requestManager.getEventMethod(requestUri);
283:                    if (eventType != null && eventPath != null
284:                            && eventMethod != null) {
285:                        try {
286:                            long eventStartTime = System.currentTimeMillis();
287:                            eventReturnString = this 
288:                                    .runEvent(request, response, eventType,
289:                                            eventPath, eventMethod);
290:                            ServerHitBin.countEvent(cname + "." + eventMethod,
291:                                    request, eventStartTime, System
292:                                            .currentTimeMillis()
293:                                            - eventStartTime, userLogin,
294:                                    delegator);
295:                            if (eventReturnString == null)
296:                                nextView = "none:";
297:                        } catch (EventHandlerException e) {
298:                            // check to see if there is an "error" response, if so go there and make an request error message
299:                            String tryErrorMsg = requestManager
300:                                    .getRequestAttribute(requestUri, "error");
301:
302:                            if (tryErrorMsg != null) {
303:                                eventReturnString = "error";
304:                                request.setAttribute("_ERROR_MESSAGE_",
305:                                        "Error calling event: " + e.toString());
306:                            } else {
307:                                throw new RequestHandlerException(
308:                                        "Error calling event and no error repsonse was specified",
309:                                        e);
310:                            }
311:                        }
312:                    }
313:                }
314:
315:                // Process the eventReturn.
316:                String eventReturn = requestManager.getRequestAttribute(
317:                        requestUri, eventReturnString);
318:
319:                if (Debug.verboseOn())
320:                    Debug.logVerbose("[Response Qualified]: " + eventReturn,
321:                            module);
322:
323:                // Set the next view
324:                if (eventReturn != null && !"success".equals(eventReturnString))
325:                    nextView = eventReturn;
326:                if (Debug.verboseOn())
327:                    Debug.logVerbose("[Event Response Mapping]: " + nextView,
328:                            module);
329:
330:                // get the previous request info
331:                String previousRequest = (String) request.getSession()
332:                        .getAttribute("_PREVIOUS_REQUEST_");
333:                String loginPass = (String) request
334:                        .getAttribute("_LOGIN_PASSED_");
335:
336:                if (Debug.verboseOn())
337:                    Debug.logVerbose("[RequestHandler]: previousRequest - "
338:                            + previousRequest + " (" + loginPass + ")", module);
339:
340:                // if previous request exists, and a login just succeeded, do that now.
341:                if (previousRequest != null && loginPass != null
342:                        && loginPass.equalsIgnoreCase("TRUE")) {
343:                    request.getSession().removeAttribute("_PREVIOUS_REQUEST_");
344:                    if (Debug.infoOn())
345:                        Debug.logInfo("[Doing Previous Request]: "
346:                                + previousRequest, module);
347:                    doRequest(request, response, previousRequest, userLogin,
348:                            delegator);
349:                    return; // this is needed or else we will run the view twice
350:                }
351:
352:                String successView = requestManager.getViewName(requestUri);
353:                if ("success".equals(eventReturnString)
354:                        && successView.startsWith("request:")) {
355:                    // chains will override any url defined views; but we will save the view for the very end
356:                    if (nextView != null) {
357:                        request.setAttribute("_POST_CHAIN_VIEW_", nextView);
358:                    }
359:                    nextView = successView;
360:                }
361:
362:                // Make sure we have some sort of response to go to
363:                if (nextView == null)
364:                    nextView = successView;
365:                if (Debug.verboseOn())
366:                    Debug.logVerbose("[Current View]: " + nextView, module);
367:
368:                // Handle the responses - chains/views
369:                if (nextView != null && nextView.startsWith("request:")) {
370:                    // chained request
371:                    Debug
372:                            .log(
373:                                    "[RequestHandler.doRequest]: Response is a chained request.",
374:                                    module);
375:                    nextView = nextView.substring(8);
376:                    doRequest(request, response, nextView, userLogin, delegator);
377:                    return; // this just to be safe; not really needed
378:
379:                }
380:
381:                // handle views
382:                else {
383:                    // first invoke the post-processor events.
384:                    Collection postProcEvents = requestManager
385:                            .getPostProcessor();
386:                    if (postProcEvents != null) {
387:                        Iterator i = postProcEvents.iterator();
388:
389:                        while (i.hasNext()) {
390:                            Map eventMap = (HashMap) i.next();
391:                            String eType = (String) eventMap
392:                                    .get(ConfigXMLReader.EVENT_TYPE);
393:                            String ePath = (String) eventMap
394:                                    .get(ConfigXMLReader.EVENT_PATH);
395:                            String eMeth = (String) eventMap
396:                                    .get(ConfigXMLReader.EVENT_METHOD);
397:                            try {
398:                                String returnString = this .runEvent(request,
399:                                        response, eType, ePath, eMeth);
400:                                if (returnString != null
401:                                        && !returnString
402:                                                .equalsIgnoreCase("success"))
403:                                    throw new EventHandlerException(
404:                                            "Post-Processor event did not return 'success'.");
405:                                else if (returnString == null)
406:                                    nextView = "none:";
407:                            } catch (EventHandlerException e) {
408:                                Debug.logError(e, module);
409:                            }
410:                        }
411:                    }
412:
413:                    // check for a url for redirection
414:                    if (nextView != null && nextView.startsWith("url:")) {
415:                        Debug
416:                                .log(
417:                                        "[RequestHandler.doRequest]: Response is a URL redirect.",
418:                                        module);
419:                        nextView = nextView.substring(4);
420:                        callRedirect(nextView, response);
421:                    }
422:
423:                    // check for a View
424:                    else if (nextView != null && nextView.startsWith("view:")) {
425:                        Debug
426:                                .log(
427:                                        "[RequestHandler.doRequest]: Response is a view.",
428:                                        module);
429:                        nextView = nextView.substring(5);
430:                        renderView(nextView, requestManager
431:                                .allowExtView(requestUri), request, response);
432:                    }
433:
434:                    // check for a no dispatch return (meaning the return was processed by the event
435:                    else if (nextView != null && nextView.startsWith("none:")) {
436:                        Debug
437:                                .log(
438:                                        "[RequestHandler.doRequest]: Response is handled by the event.",
439:                                        module);
440:                    }
441:
442:                    // a page request
443:                    else if (nextView != null) {
444:                        Debug
445:                                .log(
446:                                        "[RequestHandler.doRequest]: Response is a page.",
447:                                        module);
448:                        renderView(nextView, requestManager
449:                                .allowExtView(requestUri), request, response);
450:                    }
451:
452:                    // unknown request
453:                    else {
454:                        throw new RequestHandlerException(
455:                                "Illegal request; handler could not process the request.");
456:                    }
457:                }
458:            }
459:
460:            /** Find the event handler and invoke an event. */
461:            public String runEvent(HttpServletRequest request,
462:                    HttpServletResponse response, String type, String path,
463:                    String method) throws EventHandlerException {
464:                EventHandler eventHandler = eventFactory.getEventHandler(type);
465:                return eventHandler.invoke(path, method, request, response);
466:            }
467:
468:            /** Returns the default error page for this request. */
469:            public String getDefaultErrorPage(HttpServletRequest request) {
470:                //String requestUri = RequestHandler.getRequestUri(request.getPathInfo());
471:                //return requestManager.getErrorPage(requestUri);
472:                return requestManager.getDefaultErrorPage();
473:            }
474:
475:            /** Returns the RequestManager Object. */
476:            public RequestManager getRequestManager() {
477:                return requestManager;
478:            }
479:
480:            /** Returns the ServletContext Object. */
481:            public ServletContext getServletContext() {
482:                return context;
483:            }
484:
485:            /** Returns the ViewFactory Object. */
486:            public ViewFactory getViewFactory() {
487:                return viewFactory;
488:            }
489:
490:            /** Returns the EventFactory Object. */
491:            public EventFactory getEventFactory() {
492:                return eventFactory;
493:            }
494:
495:            public static String getRequestUri(String path) {
496:                List pathInfo = StringUtil.split(path, "/");
497:                if (((String) pathInfo.get(0)).indexOf('?') > -1) {
498:                    return ((String) pathInfo.get(0)).substring(0,
499:                            ((String) pathInfo.get(0)).indexOf('?'));
500:                } else {
501:                    return (String) pathInfo.get(0);
502:                }
503:            }
504:
505:            public static String getNextPageUri(String path) {
506:                List pathInfo = StringUtil.split(path, "/");
507:                String nextPage = null;
508:                for (int i = 1; i < pathInfo.size(); i++) {
509:                    String element = (String) pathInfo.get(i);
510:                    if (element.indexOf('~') != 0) {
511:                        if (element.indexOf('?') > -1) {
512:                            element = element
513:                                    .substring(0, element.indexOf('?'));
514:                        }
515:                        if (i == 1) {
516:                            nextPage = element;
517:                        } else {
518:                            nextPage = nextPage + "/" + element;
519:                        }
520:                    }
521:                }
522:                return nextPage;
523:            }
524:
525:            private void callRedirect(String url, HttpServletResponse resp)
526:                    throws RequestHandlerException {
527:                if (Debug.infoOn())
528:                    Debug.logInfo("[Sending redirect]: " + url, module);
529:                try {
530:                    resp.sendRedirect(url);
531:                } catch (IOException ioe) {
532:                    throw new RequestHandlerException(ioe.getMessage(), ioe);
533:                } catch (IllegalStateException ise) {
534:                    throw new RequestHandlerException(ise.getMessage(), ise);
535:                }
536:            }
537:
538:            private void renderView(String view, boolean allowExtView,
539:                    HttpServletRequest req, HttpServletResponse resp)
540:                    throws RequestHandlerException {
541:                GenericValue userLogin = (GenericValue) req.getSession()
542:                        .getAttribute("userLogin");
543:                GenericDelegator delegator = (GenericDelegator) req
544:                        .getAttribute("delegator");
545:                // workaraound if we are in the root webapp
546:                String cname = UtilHttp.getApplicationName(req);
547:                String oldView = view;
548:
549:                if (view != null && view.length() > 0 && view.charAt(0) == '/')
550:                    view = view.substring(1);
551:
552:                // if the view name starts with the control servlet name and a /, then it was an 
553:                // attempt to override the default view with a call back into the control servlet,
554:                // so just get the target view name and use that
555:                String servletName = req.getServletPath().substring(1);
556:
557:                Debug.logInfo("servletName=" + servletName + ", view=" + view,
558:                        module);
559:                if (view.startsWith(servletName + "/")) {
560:                    view = view.substring(servletName.length() + 1);
561:                    Debug
562:                            .logInfo(
563:                                    "a manual control servlet request was received, removing control servlet path resulting in: view="
564:                                            + view, module);
565:                }
566:
567:                if (Debug.verboseOn())
568:                    Debug.logVerbose("[Getting View Map]: " + view, module);
569:
570:                // before mapping the view, set a session attribute so we know where we are
571:                req.setAttribute("_CURRENT_VIEW_", view);
572:
573:                String viewType = requestManager.getViewType(view);
574:                String tempView = requestManager.getViewPage(view);
575:                String nextPage = null;
576:
577:                if (tempView == null) {
578:                    if (!allowExtView) {
579:                        throw new RequestHandlerException("No view to render.");
580:                    } else {
581:                        nextPage = "/" + oldView;
582:                    }
583:                } else {
584:                    nextPage = tempView;
585:                }
586:
587:                if (Debug.verboseOn())
588:                    Debug.logVerbose("[Mapped To]: " + nextPage, module);
589:
590:                long viewStartTime = System.currentTimeMillis();
591:
592:                // setup chararcter encoding and content type
593:                String charset = getServletContext()
594:                        .getInitParameter("charset");
595:
596:                if (charset == null || charset.length() == 0)
597:                    charset = req.getCharacterEncoding();
598:                if (charset == null || charset.length() == 0)
599:                    charset = "UTF-8";
600:
601:                String viewCharset = requestManager.getViewEncoding(view);
602:                //NOTE: if the viewCharset is "none" then no charset will be used
603:                if (viewCharset != null && viewCharset.length() > 0)
604:                    charset = viewCharset;
605:
606:                if (!"none".equals(charset)) {
607:                    try {
608:                        req.setCharacterEncoding(charset);
609:                    } catch (UnsupportedEncodingException e) {
610:                        throw new RequestHandlerException(
611:                                "Could not set character encoding to "
612:                                        + charset, e);
613:                    } catch (IllegalStateException e) {
614:                        Debug
615:                                .logInfo(
616:                                        e,
617:                                        "Could not set character encoding to "
618:                                                + charset
619:                                                + ", something has probably already committed the stream",
620:                                        module);
621:                    }
622:                }
623:
624:                // setup content type
625:                String contentType = "text/html";
626:                String viewContentType = requestManager
627:                        .getViewContentType(view);
628:                if (viewContentType != null && viewContentType.length() > 0)
629:                    contentType = viewContentType;
630:
631:                if (charset.length() > 0 && !"none".equals(charset)) {
632:                    resp.setContentType(contentType + "; charset=" + charset);
633:                } else {
634:                    resp.setContentType(contentType);
635:                }
636:
637:                if (Debug.verboseOn())
638:                    Debug.logVerbose("The ContentType for the " + view
639:                            + " view is: " + contentType, module);
640:
641:                try {
642:                    if (Debug.verboseOn())
643:                        Debug.logVerbose("Rendering view [" + nextPage
644:                                + "] of type [" + viewType + "]", module);
645:                    ViewHandler vh = viewFactory.getViewHandler(viewType);
646:                    //Debug.log("Obtained View Handler : " + vh, module);
647:                    vh.render(view, nextPage, requestManager.getViewInfo(view),
648:                            contentType, charset, req, resp);
649:                    //Debug.log("Rendered View : " + view + " : " + vh, module);
650:                } catch (ViewHandlerException e) {
651:                    Throwable throwable = e.getNested() != null ? e.getNested()
652:                            : e;
653:
654:                    throw new RequestHandlerException(e.getNonNestedMessage(),
655:                            throwable);
656:                }
657:
658:                // before getting the view generation time flush the response output to get more consistent results
659:                try {
660:                    resp.flushBuffer();
661:                } catch (java.io.IOException e) {
662:                    throw new RequestHandlerException(
663:                            "Error flushing response buffer", e);
664:                }
665:
666:                String vname = (String) req.getAttribute("_CURRENT_VIEW_");
667:
668:                if (vname != null) {
669:                    ServerHitBin.countView(cname + "." + vname, req,
670:                            viewStartTime, System.currentTimeMillis()
671:                                    - viewStartTime, userLogin, delegator);
672:                }
673:            }
674:
675:            public String makeLink(HttpServletRequest request,
676:                    HttpServletResponse response, String url) {
677:                return makeLink(request, response, url, false, false, false);
678:            }
679:
680:            public String makeLink(HttpServletRequest request,
681:                    HttpServletResponse response, String url, boolean fullPath,
682:                    boolean secure, boolean encode) {
683:                GenericDelegator delegator = (GenericDelegator) request
684:                        .getAttribute("delegator");
685:                String webSiteId = WebSiteWorker.getWebSiteId(request);
686:
687:                String httpsPort = null;
688:                String httpsServer = null;
689:                String httpPort = null;
690:                String httpServer = null;
691:                Boolean enableHttps = null;
692:
693:                // load the properties from the website entity        
694:                GenericValue webSite = null;
695:                if (webSiteId != null) {
696:                    try {
697:                        webSite = delegator.findByPrimaryKeyCache("WebSite",
698:                                UtilMisc.toMap("webSiteId", webSiteId));
699:                        if (webSite != null) {
700:                            httpsPort = webSite.getString("httpsPort");
701:                            httpsServer = webSite.getString("httpsHost");
702:                            httpPort = webSite.getString("httpPort");
703:                            httpServer = webSite.getString("httpHost");
704:                            enableHttps = webSite.getBoolean("enableHttps");
705:                        }
706:                    } catch (GenericEntityException e) {
707:                        Debug
708:                                .logWarning(
709:                                        e,
710:                                        "Problems with WebSite entity; using global defaults",
711:                                        module);
712:                    }
713:                }
714:
715:                // fill in any missing properties with fields from the global file
716:                if (httpsPort == null)
717:                    httpsPort = UtilProperties.getPropertyValue(
718:                            "url.properties", "port.https", "443");
719:                if (httpServer == null)
720:                    httpsServer = UtilProperties.getPropertyValue(
721:                            "url.properties", "force.https.host");
722:                if (httpPort == null)
723:                    httpPort = UtilProperties.getPropertyValue(
724:                            "url.properties", "port.http", "80");
725:                if (httpServer == null)
726:                    httpServer = UtilProperties.getPropertyValue(
727:                            "url.properties", "force.http.host");
728:                if (enableHttps == null)
729:                    enableHttps = new Boolean(UtilProperties
730:                            .propertyValueEqualsIgnoreCase("url.properties",
731:                                    "port.https.enabled", "Y"));
732:
733:                // create the path the the control servlet
734:                String controlPath = (String) request
735:                        .getAttribute("_CONTROL_PATH_");
736:
737:                String requestUri = RequestHandler.getRequestUri(url);
738:                StringBuffer newURL = new StringBuffer();
739:
740:                boolean useHttps = enableHttps.booleanValue();
741:                if (useHttps || fullPath || secure) {
742:                    if (secure
743:                            || (useHttps
744:                                    && requestManager.requiresHttps(requestUri) && !request
745:                                    .isSecure())) {
746:                        String server = httpsServer;
747:
748:                        if (server == null || server.length() == 0) {
749:                            server = request.getServerName();
750:                        }
751:                        newURL.append("https://");
752:                        newURL.append(server);
753:                        if (!httpsPort.equals("443")) {
754:                            newURL.append(":" + httpsPort);
755:                        }
756:                    } else if (fullPath
757:                            || (useHttps
758:                                    && !requestManager
759:                                            .requiresHttps(requestUri) && request
760:                                    .isSecure())) {
761:                        String server = httpServer;
762:
763:                        if (server == null || server.length() == 0) {
764:                            server = request.getServerName();
765:                        }
766:                        newURL.append("http://");
767:                        newURL.append(server);
768:                        if (!httpPort.equals("80")) {
769:                            newURL.append(":" + httpPort);
770:                        }
771:                    }
772:                }
773:
774:                newURL.append(controlPath);
775:                newURL.append(url);
776:                String encodedUrl = null;
777:                if (response != null && !encode) {
778:                    encodedUrl = response.encodeURL(newURL.toString());
779:                } else {
780:                    if (encode) {
781:                        String sessionId = request.getSession().getId();
782:                        newURL.append(";jsessionid=" + sessionId);
783:                    }
784:                    encodedUrl = newURL.toString();
785:                }
786:
787:                return encodedUrl;
788:            }
789:
790:            public static String makeUrl(HttpServletRequest request,
791:                    HttpServletResponse response, String url) {
792:                return makeUrl(request, response, url, false, false, false);
793:            }
794:
795:            public static String makeUrl(HttpServletRequest request,
796:                    HttpServletResponse response, String url, boolean fullPath,
797:                    boolean secure, boolean encode) {
798:                ServletContext ctx = (ServletContext) request
799:                        .getAttribute("servletContext");
800:                RequestHandler rh = (RequestHandler) ctx
801:                        .getAttribute("_REQUEST_HANDLER_");
802:                return rh.makeLink(request, response, url, fullPath, secure,
803:                        encode);
804:            }
805:
806:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.