1   /**
2    * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portal.servlet;
24  
25  import com.liferay.portal.NoSuchLayoutException;
26  import com.liferay.portal.deploy.hot.PluginPackageHotDeployListener;
27  import com.liferay.portal.events.EventsProcessor;
28  import com.liferay.portal.events.StartupAction;
29  import com.liferay.portal.kernel.deploy.hot.HotDeployUtil;
30  import com.liferay.portal.kernel.events.ActionException;
31  import com.liferay.portal.kernel.job.Scheduler;
32  import com.liferay.portal.kernel.log.Log;
33  import com.liferay.portal.kernel.log.LogFactoryUtil;
34  import com.liferay.portal.kernel.plugin.PluginPackage;
35  import com.liferay.portal.kernel.pop.MessageListener;
36  import com.liferay.portal.kernel.search.Indexer;
37  import com.liferay.portal.kernel.search.IndexerRegistryUtil;
38  import com.liferay.portal.kernel.servlet.PortletSessionTracker;
39  import com.liferay.portal.kernel.servlet.ProtectedServletRequest;
40  import com.liferay.portal.kernel.util.ContentTypes;
41  import com.liferay.portal.kernel.util.GetterUtil;
42  import com.liferay.portal.kernel.util.HttpUtil;
43  import com.liferay.portal.kernel.util.InstancePool;
44  import com.liferay.portal.kernel.util.ParamUtil;
45  import com.liferay.portal.kernel.util.PortalClassLoaderUtil;
46  import com.liferay.portal.kernel.util.PortalInitableUtil;
47  import com.liferay.portal.kernel.util.ReleaseInfo;
48  import com.liferay.portal.kernel.util.StringPool;
49  import com.liferay.portal.kernel.util.Validator;
50  import com.liferay.portal.kernel.xml.Document;
51  import com.liferay.portal.kernel.xml.DocumentException;
52  import com.liferay.portal.kernel.xml.Element;
53  import com.liferay.portal.kernel.xml.SAXReaderUtil;
54  import com.liferay.portal.model.Company;
55  import com.liferay.portal.model.Group;
56  import com.liferay.portal.model.GroupConstants;
57  import com.liferay.portal.model.Layout;
58  import com.liferay.portal.model.Portlet;
59  import com.liferay.portal.model.PortletApp;
60  import com.liferay.portal.model.PortletFilter;
61  import com.liferay.portal.model.PortletURLListener;
62  import com.liferay.portal.model.User;
63  import com.liferay.portal.pop.POPServerUtil;
64  import com.liferay.portal.security.auth.CompanyThreadLocal;
65  import com.liferay.portal.security.auth.PrincipalException;
66  import com.liferay.portal.security.auth.PrincipalThreadLocal;
67  import com.liferay.portal.service.CompanyLocalServiceUtil;
68  import com.liferay.portal.service.GroupLocalServiceUtil;
69  import com.liferay.portal.service.LayoutLocalServiceUtil;
70  import com.liferay.portal.service.LayoutTemplateLocalServiceUtil;
71  import com.liferay.portal.service.PortletLocalServiceUtil;
72  import com.liferay.portal.service.ThemeLocalServiceUtil;
73  import com.liferay.portal.service.UserLocalServiceUtil;
74  import com.liferay.portal.struts.PortletRequestProcessor;
75  import com.liferay.portal.struts.StrutsUtil;
76  import com.liferay.portal.util.ContentUtil;
77  import com.liferay.portal.util.Portal;
78  import com.liferay.portal.util.PortalInstances;
79  import com.liferay.portal.util.PortalUtil;
80  import com.liferay.portal.util.PropsKeys;
81  import com.liferay.portal.util.PropsUtil;
82  import com.liferay.portal.util.PropsValues;
83  import com.liferay.portal.util.ShutdownUtil;
84  import com.liferay.portal.util.WebKeys;
85  import com.liferay.portal.velocity.VelocityContextPool;
86  import com.liferay.portal.webdav.WebDAVStorage;
87  import com.liferay.portal.webdav.WebDAVUtil;
88  import com.liferay.portlet.PortletConfigFactory;
89  import com.liferay.portlet.PortletFilterFactory;
90  import com.liferay.portlet.PortletInstanceFactoryUtil;
91  import com.liferay.portlet.PortletURLListenerFactory;
92  import com.liferay.portlet.social.model.SocialActivityInterpreter;
93  import com.liferay.portlet.social.model.SocialRequestInterpreter;
94  import com.liferay.portlet.social.model.impl.SocialActivityInterpreterImpl;
95  import com.liferay.portlet.social.model.impl.SocialRequestInterpreterImpl;
96  import com.liferay.portlet.social.service.SocialActivityInterpreterLocalServiceUtil;
97  import com.liferay.portlet.social.service.SocialRequestInterpreterLocalServiceUtil;
98  import com.liferay.util.servlet.DynamicServletRequest;
99  import com.liferay.util.servlet.EncryptedServletRequest;
100 
101 import java.io.IOException;
102 
103 import java.util.Iterator;
104 import java.util.List;
105 import java.util.Set;
106 
107 import javax.portlet.PortletConfig;
108 import javax.portlet.PortletContext;
109 import javax.portlet.PortletException;
110 
111 import javax.servlet.ServletContext;
112 import javax.servlet.ServletException;
113 import javax.servlet.http.HttpServletRequest;
114 import javax.servlet.http.HttpServletResponse;
115 import javax.servlet.http.HttpSession;
116 import javax.servlet.jsp.PageContext;
117 
118 import org.apache.struts.Globals;
119 import org.apache.struts.action.ActionServlet;
120 import org.apache.struts.action.RequestProcessor;
121 import org.apache.struts.config.ControllerConfig;
122 import org.apache.struts.config.ModuleConfig;
123 import org.apache.struts.tiles.TilesUtilImpl;
124 
125 /**
126  * <a href="MainServlet.java.html"><b><i>View Source</i></b></a>
127  *
128  * @author Brian Wing Shun Chan
129  * @author Jorge Ferrer
130  * @author Brian Myunghun Kim
131  *
132  */
133 public class MainServlet extends ActionServlet {
134 
135     public void init() throws ServletException {
136 
137         // Initialize
138 
139         if (_log.isDebugEnabled()) {
140             _log.debug("Initialize");
141         }
142 
143         super.init();
144 
145         // Startup events
146 
147         if (_log.isDebugEnabled()) {
148             _log.debug("Process startup events");
149         }
150 
151         try {
152             StartupAction startupAction = new StartupAction();
153 
154             startupAction.run(null);
155         }
156         catch (RuntimeException re) {
157             ShutdownUtil.shutdown(0);
158 
159             throw new ServletException(re);
160         }
161         catch (ActionException ae) {
162             _log.error(ae, ae);
163         }
164 
165         // Velocity
166 
167         String contextPath = PortalUtil.getPathContext();
168 
169         ServletContext servletContext = getServletContext();
170 
171         VelocityContextPool.put(contextPath, servletContext);
172 
173         // Plugin package
174 
175         if (_log.isDebugEnabled()) {
176             _log.debug("Initialize plugin package");
177         }
178 
179         PluginPackage pluginPackage = null;
180 
181         try {
182             pluginPackage =
183                 PluginPackageHotDeployListener.readPluginPackage(
184                     servletContext);
185         }
186         catch (Exception e) {
187             _log.error(e, e);
188         }
189 
190         // Portlets
191 
192         if (_log.isDebugEnabled()) {
193             _log.debug("Initialize portlets");
194         }
195 
196         List<Portlet> portlets = null;
197 
198         try {
199             String[] xmls = new String[] {
200                 HttpUtil.URLtoString(servletContext.getResource(
201                     "/WEB-INF/" + Portal.PORTLET_XML_FILE_NAME_CUSTOM)),
202                 HttpUtil.URLtoString(servletContext.getResource(
203                     "/WEB-INF/portlet-ext.xml")),
204                 HttpUtil.URLtoString(servletContext.getResource(
205                     "/WEB-INF/liferay-portlet.xml")),
206                 HttpUtil.URLtoString(servletContext.getResource(
207                     "/WEB-INF/liferay-portlet-ext.xml")),
208                 HttpUtil.URLtoString(servletContext.getResource(
209                     "/WEB-INF/web.xml"))
210             };
211 
212             PortletLocalServiceUtil.initEAR(
213                 servletContext, xmls, pluginPackage);
214 
215             portlets = PortletLocalServiceUtil.getPortlets();
216 
217             for (int i = 0; i < portlets.size(); i++) {
218                 Portlet portlet = portlets.get(i);
219 
220                 if (i == 0) {
221                     initPortletApp(portlet, servletContext);
222                 }
223 
224                 PortletInstanceFactoryUtil.create(portlet, servletContext);
225             }
226         }
227         catch (Exception e) {
228             _log.error(e, e);
229         }
230 
231         // Layout templates
232 
233         if (_log.isDebugEnabled()) {
234             _log.debug("Initialize layout templates");
235         }
236 
237         try {
238             String[] xmls = new String[] {
239                 HttpUtil.URLtoString(servletContext.getResource(
240                     "/WEB-INF/liferay-layout-templates.xml")),
241                 HttpUtil.URLtoString(servletContext.getResource(
242                     "/WEB-INF/liferay-layout-templates-ext.xml"))
243             };
244 
245             LayoutTemplateLocalServiceUtil.init(
246                 servletContext, xmls, pluginPackage);
247         }
248         catch (Exception e) {
249             _log.error(e, e);
250         }
251 
252         // Look and feel
253 
254         if (_log.isDebugEnabled()) {
255             _log.debug("Initialize look and feel");
256         }
257 
258         try {
259             String[] xmls = new String[] {
260                 HttpUtil.URLtoString(servletContext.getResource(
261                     "/WEB-INF/liferay-look-and-feel.xml")),
262                 HttpUtil.URLtoString(servletContext.getResource(
263                     "/WEB-INF/liferay-look-and-feel-ext.xml"))
264             };
265 
266             ThemeLocalServiceUtil.init(
267                 servletContext, null, true, xmls, pluginPackage);
268         }
269         catch (Exception e) {
270             _log.error(e, e);
271         }
272 
273         // Indexer
274 
275         if (_log.isDebugEnabled()) {
276             _log.debug("Indexer");
277         }
278 
279         try {
280             Iterator<Portlet> itr = portlets.iterator();
281 
282             while (itr.hasNext()) {
283                 Portlet portlet = itr.next();
284 
285                 String indexerClass = portlet.getIndexerClass();
286 
287                 if (!portlet.isActive() || Validator.isNull(indexerClass)) {
288                     continue;
289                 }
290 
291                 Indexer indexer = (Indexer)InstancePool.get(indexerClass);
292 
293                 for (String modelClassName : indexer.getClassNames()) {
294                     IndexerRegistryUtil.register(modelClassName, indexer);
295                 }
296             }
297         }
298         catch (Exception e) {
299             _log.error(e, e);
300         }
301 
302         // Scheduler
303 
304         if (_log.isDebugEnabled()) {
305             _log.debug("Scheduler");
306         }
307 
308         try {
309             if (PropsValues.SCHEDULER_ENABLED) {
310                 for (String className : PropsValues.SCHEDULER_CLASSES) {
311                     Scheduler scheduler = (Scheduler)InstancePool.get(
312                         className);
313 
314                     scheduler.schedule();
315                 }
316 
317                 Iterator<Portlet> itr = portlets.iterator();
318 
319                 while (itr.hasNext()) {
320                     Portlet portlet = itr.next();
321 
322                     String className = portlet.getSchedulerClass();
323 
324                     if (!portlet.isActive() || Validator.isNull(className)) {
325                         continue;
326                     }
327 
328                     Scheduler scheduler = (Scheduler)InstancePool.get(
329                         className);
330 
331                     scheduler.schedule();
332                 }
333             }
334         }
335         catch (Exception e) {
336             _log.error(e, e);
337         }
338 
339         // POP message listener
340 
341         if (_log.isDebugEnabled()) {
342             _log.debug("POP message listener");
343         }
344 
345         try {
346             Iterator<Portlet> itr = portlets.iterator();
347 
348             while (itr.hasNext()) {
349                 Portlet portlet = itr.next();
350 
351                 MessageListener popMessageListener =
352                     portlet.getPopMessageListenerInstance();
353 
354                 if (!portlet.isActive() || (popMessageListener == null)) {
355                     continue;
356                 }
357 
358                 POPServerUtil.addListener(popMessageListener);
359             }
360         }
361         catch (Exception e) {
362             _log.error(e, e);
363         }
364 
365         // Social activity interpreter
366 
367         if (_log.isDebugEnabled()) {
368             _log.debug("Social activity interpreter");
369         }
370 
371         try {
372             Iterator<Portlet> itr = portlets.iterator();
373 
374             while (itr.hasNext()) {
375                 Portlet portlet = itr.next();
376 
377                 SocialActivityInterpreter socialActivityInterpreter =
378                     portlet.getSocialActivityInterpreterInstance();
379 
380                 if (!portlet.isActive() ||
381                     (socialActivityInterpreter == null)) {
382 
383                     continue;
384                 }
385 
386                 socialActivityInterpreter = new SocialActivityInterpreterImpl(
387                     portlet.getPortletId(), socialActivityInterpreter);
388 
389                 SocialActivityInterpreterLocalServiceUtil.
390                     addActivityInterpreter(socialActivityInterpreter);
391             }
392         }
393         catch (Exception e) {
394             _log.error(e, e);
395         }
396 
397         // Social request interpreter
398 
399         if (_log.isDebugEnabled()) {
400             _log.debug("Social request interpreter");
401         }
402 
403         try {
404             Iterator<Portlet> itr = portlets.iterator();
405 
406             while (itr.hasNext()) {
407                 Portlet portlet = itr.next();
408 
409                 SocialRequestInterpreter socialRequestInterpreter =
410                     portlet.getSocialRequestInterpreterInstance();
411 
412                 if (!portlet.isActive() || (socialRequestInterpreter == null)) {
413                     continue;
414                 }
415 
416                 socialRequestInterpreter = new SocialRequestInterpreterImpl(
417                     portlet.getPortletId(), socialRequestInterpreter);
418 
419                 SocialRequestInterpreterLocalServiceUtil.
420                     addRequestInterpreter(socialRequestInterpreter);
421             }
422         }
423         catch (Exception e) {
424             _log.error(e, e);
425         }
426 
427         // WebDAV storage
428 
429         if (_log.isDebugEnabled()) {
430             _log.debug("WebDAV storage");
431         }
432 
433         try {
434             Iterator<Portlet> itr = portlets.iterator();
435 
436             while (itr.hasNext()) {
437                 Portlet portlet = itr.next();
438 
439                 WebDAVStorage webDAVStorage =
440                     portlet.getWebDAVStorageInstance();
441 
442                 if (!portlet.isActive() || (webDAVStorage == null)) {
443                     continue;
444                 }
445 
446                 webDAVStorage.setToken(portlet.getWebDAVStorageToken());
447 
448                 WebDAVUtil.addStorage(webDAVStorage);
449             }
450         }
451         catch (Exception e) {
452             _log.error(e, e);
453         }
454 
455         // Check web settings
456 
457         if (_log.isDebugEnabled()) {
458             _log.debug("Check web settings");
459         }
460 
461         try {
462             String xml = HttpUtil.URLtoString(
463                 servletContext.getResource("/WEB-INF/web.xml"));
464 
465             checkWebSettings(xml);
466         }
467         catch (Exception e) {
468             _log.error(e, e);
469         }
470 
471         // Global startup events
472 
473         if (_log.isDebugEnabled()) {
474             _log.debug("Process global startup events");
475         }
476 
477         try {
478             EventsProcessor.process(
479                 PropsKeys.GLOBAL_STARTUP_EVENTS,
480                 PropsValues.GLOBAL_STARTUP_EVENTS);
481         }
482         catch (Exception e) {
483             _log.error(e, e);
484         }
485 
486         // Companies
487 
488         String[] webIds = PortalInstances.getWebIds();
489 
490         for (int i = 0; i < webIds.length; i++) {
491             PortalInstances.initCompany(servletContext, webIds[i]);
492         }
493 
494         // See LEP-2885. Don't flush hot deploy events until after the portal
495         // has initialized.
496 
497         PortalInitableUtil.flushInitables();
498         HotDeployUtil.flushPrematureEvents();
499     }
500 
501     public void callParentService(
502             HttpServletRequest request, HttpServletResponse response)
503         throws IOException, ServletException {
504 
505         super.service(request, response);
506     }
507 
508     public void service(
509             HttpServletRequest request, HttpServletResponse response)
510         throws IOException, ServletException {
511 
512         if (_log.isDebugEnabled()) {
513             _log.debug("Process service request");
514         }
515 
516         if (ShutdownUtil.isShutdown()) {
517             response.setContentType(ContentTypes.TEXT_HTML_UTF8);
518 
519             String html = ContentUtil.get(
520                 "com/liferay/portal/dependencies/shutdown.html");
521 
522             response.getOutputStream().print(html);
523 
524             return;
525         }
526 
527         HttpSession session = request.getSession();
528 
529         // Company id
530 
531         long companyId = PortalInstances.getCompanyId(request);
532 
533         //CompanyThreadLocal.setCompanyId(companyId);
534 
535         // Portal port
536 
537         PortalUtil.setPortalPort(request);
538 
539         // CTX
540 
541         ServletContext servletContext = getServletContext();
542 
543         request.setAttribute(WebKeys.CTX, servletContext);
544 
545         // Struts module config
546 
547         ModuleConfig moduleConfig = getModuleConfig(request);
548 
549         // Portlet session tracker
550 
551         if (session.getAttribute(WebKeys.PORTLET_SESSION_TRACKER) == null ) {
552             session.setAttribute(
553                 WebKeys.PORTLET_SESSION_TRACKER,
554                 PortletSessionTracker.getInstance());
555         }
556 
557         // Portlet Request Processor
558 
559         PortletRequestProcessor portletReqProcessor =
560             (PortletRequestProcessor)servletContext.getAttribute(
561                 WebKeys.PORTLET_STRUTS_PROCESSOR);
562 
563         if (portletReqProcessor == null) {
564             portletReqProcessor =
565                 PortletRequestProcessor.getInstance(this, moduleConfig);
566 
567             servletContext.setAttribute(
568                 WebKeys.PORTLET_STRUTS_PROCESSOR, portletReqProcessor);
569         }
570 
571         // Tiles definitions factory
572 
573         if (servletContext.getAttribute(
574                 TilesUtilImpl.DEFINITIONS_FACTORY) == null) {
575 
576             servletContext.setAttribute(
577                 TilesUtilImpl.DEFINITIONS_FACTORY,
578                 servletContext.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY));
579         }
580 
581         Object applicationAssociate = servletContext.getAttribute(
582             WebKeys.ASSOCIATE_KEY);
583 
584         if (servletContext.getAttribute(WebKeys.ASSOCIATE_KEY) == null) {
585             servletContext.setAttribute(
586                 WebKeys.ASSOCIATE_KEY, applicationAssociate);
587         }
588 
589         // Encrypt request
590 
591         if (ParamUtil.get(request, WebKeys.ENCRYPT, false)) {
592             try {
593                 Company company = CompanyLocalServiceUtil.getCompanyById(
594                     companyId);
595 
596                 request = new EncryptedServletRequest(
597                     request, company.getKeyObj());
598             }
599             catch (Exception e) {
600             }
601         }
602 
603         // Current URL
604 
605         PortalUtil.getCurrentURL(request);
606 
607         // Login
608 
609         long userId = PortalUtil.getUserId(request);
610         String remoteUser = request.getRemoteUser();
611 
612         // Is JAAS enabled?
613 
614         if (!PropsValues.PORTAL_JAAS_ENABLE) {
615             String jRemoteUser = (String)session.getAttribute("j_remoteuser");
616 
617             if (jRemoteUser != null) {
618                 remoteUser = jRemoteUser;
619 
620                 session.removeAttribute("j_remoteuser");
621             }
622         }
623 
624         if ((userId > 0) && (remoteUser == null)) {
625             remoteUser = String.valueOf(userId);
626         }
627 
628         // WebSphere will not return the remote user unless you are
629         // authenticated AND accessing a protected path. Other servers will
630         // return the remote user for all threads associated with an
631         // authenticated user. We use ProtectedServletRequest to ensure we get
632         // similar behavior across all servers.
633 
634         request = new ProtectedServletRequest(request, remoteUser);
635 
636         if ((userId > 0) || (remoteUser != null)) {
637 
638             // Set the principal associated with this thread
639 
640             String name = String.valueOf(userId);
641 
642             if (remoteUser != null) {
643                 name = remoteUser;
644             }
645 
646             PrincipalThreadLocal.setName(name);
647         }
648 
649         if ((userId <= 0) && (remoteUser != null)) {
650             try {
651 
652                 // User id
653 
654                 userId = GetterUtil.getLong(remoteUser);
655 
656                 // Pre login events
657 
658                 EventsProcessor.process(
659                     PropsKeys.LOGIN_EVENTS_PRE, PropsValues.LOGIN_EVENTS_PRE,
660                     request, response);
661 
662                 // User
663 
664                 User user = UserLocalServiceUtil.getUserById(userId);
665 
666                 if (PropsValues.USERS_UPDATE_LAST_LOGIN) {
667                     UserLocalServiceUtil.updateLastLogin(
668                         userId, request.getRemoteAddr());
669                 }
670 
671                 // User id
672 
673                 session.setAttribute(WebKeys.USER_ID, new Long(userId));
674 
675                 // User locale
676 
677                 session.setAttribute(Globals.LOCALE_KEY, user.getLocale());
678 
679                 // Post login events
680 
681                 EventsProcessor.process(
682                     PropsKeys.LOGIN_EVENTS_POST, PropsValues.LOGIN_EVENTS_POST,
683                     request, response);
684             }
685             catch (Exception e) {
686                 _log.error(e, e);
687             }
688         }
689 
690         // Pre service events
691 
692         try {
693             EventsProcessor.process(
694                 PropsKeys.SERVLET_SERVICE_EVENTS_PRE,
695                 PropsValues.SERVLET_SERVICE_EVENTS_PRE, request, response);
696         }
697         catch (Exception e) {
698             Throwable cause = e.getCause();
699 
700             if (cause instanceof NoSuchLayoutException) {
701                 sendError(
702                     HttpServletResponse.SC_NOT_FOUND, cause, request, response);
703 
704                 return;
705             }
706             else if (cause instanceof PrincipalException) {
707                 processServicePrePrincipalException(
708                     cause, userId, request, response);
709 
710                 return;
711             }
712 
713             _log.error(e, e);
714 
715             request.setAttribute(PageContext.EXCEPTION, e);
716 
717             StrutsUtil.forward(
718                 PropsValues.SERVLET_SERVICE_EVENTS_PRE_ERROR_PAGE,
719                 servletContext, request, response);
720 
721             return;
722         }
723 
724         if (request.getAttribute(WebKeys.THEME_DISPLAY) == null) {
725             return;
726         }
727 
728         try {
729 
730             // Struts service
731 
732             callParentService(request, response);
733         }
734         finally {
735 
736             // Post service events
737 
738             try {
739                 EventsProcessor.process(
740                     PropsKeys.SERVLET_SERVICE_EVENTS_POST,
741                     PropsValues.SERVLET_SERVICE_EVENTS_POST, request, response);
742             }
743             catch (Exception e) {
744                 _log.error(e, e);
745             }
746 
747             response.addHeader(
748                 _LIFERAY_PORTAL_REQUEST_HEADER, ReleaseInfo.getReleaseInfo());
749 
750             // Clear the company id associated with this thread
751 
752             CompanyThreadLocal.setCompanyId(0);
753 
754             // Clear the principal associated with this thread
755 
756             PrincipalThreadLocal.setName(null);
757         }
758     }
759 
760     public void destroy() {
761         List<Portlet> portlets = PortletLocalServiceUtil.getPortlets();
762 
763         // Scheduler
764 
765         if (_log.isDebugEnabled()) {
766             _log.debug("Scheduler");
767         }
768 
769         try {
770             if (PropsValues.SCHEDULER_ENABLED) {
771                 for (String className : PropsValues.SCHEDULER_CLASSES) {
772                     Scheduler scheduler = (Scheduler)InstancePool.get(
773                         className, false);
774 
775                     if (scheduler != null) {
776                         scheduler.unschedule();
777                     }
778                 }
779 
780                 Iterator<Portlet> itr = portlets.iterator();
781 
782                 while (itr.hasNext()) {
783                     Portlet portlet = itr.next();
784 
785                     String className = portlet.getSchedulerClass();
786 
787                     if (!portlet.isActive() || Validator.isNull(className)) {
788                         continue;
789                     }
790 
791                     Scheduler scheduler = (Scheduler)InstancePool.get(
792                         className, false);
793 
794                     if (scheduler != null) {
795                         scheduler.unschedule();
796                     }
797                 }
798             }
799         }
800         catch (Exception e) {
801             _log.error(e, e);
802         }
803 
804         // Portlets
805 
806         try {
807             Iterator<Portlet> itr = portlets.iterator();
808 
809             while (itr.hasNext()) {
810                 Portlet portlet = itr.next();
811 
812                 PortletInstanceFactoryUtil.destroy(portlet);
813             }
814         }
815         catch (Exception e) {
816             _log.error(e, e);
817         }
818 
819         // Companies
820 
821         long[] companyIds = PortalInstances.getCompanyIds();
822 
823         for (int i = 0; i < companyIds.length; i++) {
824             destroyCompany(companyIds[i]);
825         }
826 
827         // Global shutdown events
828 
829         if (_log.isDebugEnabled()) {
830             _log.debug("Process global shutdown events");
831         }
832 
833         try {
834             EventsProcessor.process(
835                 PropsKeys.GLOBAL_SHUTDOWN_EVENTS,
836                 PropsValues.GLOBAL_SHUTDOWN_EVENTS);
837         }
838         catch (Exception e) {
839             _log.error(e, e);
840         }
841 
842         super.destroy();
843     }
844 
845     protected void checkWebSettings(String xml) throws DocumentException {
846         Document doc = SAXReaderUtil.read(xml);
847 
848         Element root = doc.getRootElement();
849 
850         int timeout = PropsValues.SESSION_TIMEOUT;
851 
852         Element sessionConfig = root.element("session-config");
853 
854         if (sessionConfig != null) {
855             String sessionTimeout = sessionConfig.elementText(
856                 "session-timeout");
857 
858             timeout = GetterUtil.getInteger(sessionTimeout, timeout);
859         }
860 
861         PropsUtil.set(PropsKeys.SESSION_TIMEOUT, String.valueOf(timeout));
862 
863         PropsValues.SESSION_TIMEOUT = timeout;
864 
865         I18nServlet.setLanguageIds(root);
866     }
867 
868     protected void destroyCompany(long companyId) {
869         if (_log.isDebugEnabled()) {
870             _log.debug("Process shutdown events");
871         }
872 
873         try {
874             EventsProcessor.process(
875                 PropsKeys.APPLICATION_SHUTDOWN_EVENTS,
876                 PropsValues.APPLICATION_SHUTDOWN_EVENTS,
877                 new String[] {String.valueOf(companyId)});
878         }
879         catch (Exception e) {
880             _log.error(e, e);
881         }
882     }
883 
884     protected synchronized RequestProcessor getRequestProcessor(
885             ModuleConfig moduleConfig)
886         throws ServletException {
887 
888         ServletContext servletContext = getServletContext();
889 
890         String key = Globals.REQUEST_PROCESSOR_KEY + moduleConfig.getPrefix();
891 
892         RequestProcessor processor =
893             (RequestProcessor)servletContext.getAttribute(key);
894 
895         if (processor == null) {
896             ControllerConfig controllerConfig =
897                 moduleConfig.getControllerConfig();
898 
899             String processorClass = controllerConfig.getProcessorClass();
900 
901             ClassLoader classLoader = PortalClassLoaderUtil.getClassLoader();
902 
903             try {
904                 processor = (RequestProcessor)classLoader.loadClass(
905                     processorClass).newInstance();
906             }
907             catch (Exception e) {
908                 throw new ServletException(e);
909             }
910 
911             processor.init(this, moduleConfig);
912 
913             servletContext.setAttribute(key, processor);
914         }
915 
916         return processor;
917     }
918 
919     protected void initPortletApp(
920             Portlet portlet, ServletContext servletContext)
921         throws PortletException {
922 
923         PortletApp portletApp = portlet.getPortletApp();
924 
925         PortletConfig portletConfig = PortletConfigFactory.create(
926             portlet, servletContext);
927 
928         PortletContext portletContext = portletConfig.getPortletContext();
929 
930         Set<PortletFilter> portletFilters = portletApp.getPortletFilters();
931 
932         for (PortletFilter portletFilter : portletFilters) {
933             PortletFilterFactory.create(portletFilter, portletContext);
934         }
935 
936         Set<PortletURLListener> portletURLListeners =
937             portletApp.getPortletURLListeners();
938 
939         for (PortletURLListener portletURLListener : portletURLListeners) {
940             PortletURLListenerFactory.create(portletURLListener);
941         }
942     }
943 
944     protected void processServicePrePrincipalException(
945             Throwable t, long userId, HttpServletRequest request,
946             HttpServletResponse response)
947         throws IOException, ServletException {
948 
949         if (userId > 0) {
950             sendError(
951                 HttpServletResponse.SC_UNAUTHORIZED, t, request, response);
952 
953             return;
954         }
955 
956         String redirect =
957             request.getContextPath() + Portal.PATH_MAIN + "/portal/login";
958 
959         String currentURL = PortalUtil.getCurrentURL(request);
960 
961         redirect = HttpUtil.addParameter(redirect, "redirect", currentURL);
962 
963         long plid = ParamUtil.getLong(request, "p_l_id");
964 
965         if (plid > 0) {
966             try {
967                 Layout layout = LayoutLocalServiceUtil.getLayout(plid);
968 
969                 if (layout.getGroup().isStagingGroup()) {
970                     Group group = GroupLocalServiceUtil.getGroup(
971                         layout.getCompanyId(), GroupConstants.GUEST);
972 
973                     plid = group.getDefaultPublicPlid();
974                 }
975                 else if (layout.isPrivateLayout()) {
976                     plid = LayoutLocalServiceUtil.getDefaultPlid(
977                         layout.getGroupId(), false);
978                 }
979 
980                 redirect = HttpUtil.addParameter(redirect, "p_l_id", plid);
981             }
982             catch (Exception e1) {
983             }
984         }
985 
986         response.sendRedirect(redirect);
987     }
988 
989     protected void sendError(
990             int status, Throwable t, HttpServletRequest request,
991             HttpServletResponse response)
992         throws IOException, ServletException {
993 
994         DynamicServletRequest dynamicRequest = new DynamicServletRequest(
995             request);
996 
997         // Reset p_l_id or there will be an infinite loop
998 
999         dynamicRequest.setParameter("p_l_id", StringPool.BLANK);
1000
1001        PortalUtil.sendError(status, (Exception)t, dynamicRequest, response);
1002    }
1003
1004    private static final String _LIFERAY_PORTAL_REQUEST_HEADER =
1005        "Liferay-Portal";
1006
1007    private static Log _log = LogFactoryUtil.getLog(MainServlet.class);
1008
1009}