1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * The contents of this file are subject to the terms of the Liferay Enterprise
5    * Subscription License ("License"). You may not use this file except in
6    * compliance with the License. You can obtain a copy of the License by
7    * contacting Liferay, Inc. See the License for the specific language governing
8    * permissions and limitations under the License, including but not limited to
9    * distribution rights of the Software.
10   *
11   *
12   * 
13   */
14  
15  package com.liferay.portal.servlet;
16  
17  import com.liferay.portal.NoSuchLayoutException;
18  import com.liferay.portal.PortalException;
19  import com.liferay.portal.SystemException;
20  import com.liferay.portal.deploy.hot.PluginPackageHotDeployListener;
21  import com.liferay.portal.events.EventsProcessorUtil;
22  import com.liferay.portal.events.StartupAction;
23  import com.liferay.portal.kernel.deploy.hot.HotDeployUtil;
24  import com.liferay.portal.kernel.job.Scheduler;
25  import com.liferay.portal.kernel.log.Log;
26  import com.liferay.portal.kernel.log.LogFactoryUtil;
27  import com.liferay.portal.kernel.plugin.PluginPackage;
28  import com.liferay.portal.kernel.poller.PollerProcessor;
29  import com.liferay.portal.kernel.pop.MessageListener;
30  import com.liferay.portal.kernel.search.Indexer;
31  import com.liferay.portal.kernel.search.IndexerRegistryUtil;
32  import com.liferay.portal.kernel.servlet.PortletSessionTracker;
33  import com.liferay.portal.kernel.servlet.ProtectedServletRequest;
34  import com.liferay.portal.kernel.util.ContentTypes;
35  import com.liferay.portal.kernel.util.GetterUtil;
36  import com.liferay.portal.kernel.util.HttpUtil;
37  import com.liferay.portal.kernel.util.InstancePool;
38  import com.liferay.portal.kernel.util.ParamUtil;
39  import com.liferay.portal.kernel.util.PortalClassLoaderUtil;
40  import com.liferay.portal.kernel.util.PortalInitableUtil;
41  import com.liferay.portal.kernel.util.PropsKeys;
42  import com.liferay.portal.kernel.util.ReleaseInfo;
43  import com.liferay.portal.kernel.util.StringPool;
44  import com.liferay.portal.kernel.util.Validator;
45  import com.liferay.portal.kernel.xml.Document;
46  import com.liferay.portal.kernel.xml.DocumentException;
47  import com.liferay.portal.kernel.xml.Element;
48  import com.liferay.portal.kernel.xml.SAXReaderUtil;
49  import com.liferay.portal.language.LanguageResources;
50  import com.liferay.portal.model.Company;
51  import com.liferay.portal.model.Group;
52  import com.liferay.portal.model.GroupConstants;
53  import com.liferay.portal.model.Layout;
54  import com.liferay.portal.model.Portlet;
55  import com.liferay.portal.model.PortletApp;
56  import com.liferay.portal.model.PortletFilter;
57  import com.liferay.portal.model.PortletURLListener;
58  import com.liferay.portal.model.User;
59  import com.liferay.portal.poller.PollerProcessorUtil;
60  import com.liferay.portal.pop.POPServerUtil;
61  import com.liferay.portal.security.auth.PrincipalException;
62  import com.liferay.portal.security.auth.PrincipalThreadLocal;
63  import com.liferay.portal.security.permission.ResourceActionsUtil;
64  import com.liferay.portal.service.CompanyLocalServiceUtil;
65  import com.liferay.portal.service.GroupLocalServiceUtil;
66  import com.liferay.portal.service.LayoutLocalServiceUtil;
67  import com.liferay.portal.service.LayoutTemplateLocalServiceUtil;
68  import com.liferay.portal.service.PortletLocalServiceUtil;
69  import com.liferay.portal.service.ResourceActionLocalServiceUtil;
70  import com.liferay.portal.service.ResourceCodeLocalServiceUtil;
71  import com.liferay.portal.service.ThemeLocalServiceUtil;
72  import com.liferay.portal.service.UserLocalServiceUtil;
73  import com.liferay.portal.servlet.filters.i18n.I18nFilter;
74  import com.liferay.portal.struts.MultiMessageResources;
75  import com.liferay.portal.struts.PortletRequestProcessor;
76  import com.liferay.portal.struts.StrutsUtil;
77  import com.liferay.portal.util.ContentUtil;
78  import com.liferay.portal.util.ExtRegistry;
79  import com.liferay.portal.util.MaintenanceUtil;
80  import com.liferay.portal.util.Portal;
81  import com.liferay.portal.util.PortalInstances;
82  import com.liferay.portal.util.PortalUtil;
83  import com.liferay.portal.util.PropsUtil;
84  import com.liferay.portal.util.PropsValues;
85  import com.liferay.portal.util.ShutdownUtil;
86  import com.liferay.portal.util.WebKeys;
87  import com.liferay.portal.velocity.VelocityContextPool;
88  import com.liferay.portal.webdav.WebDAVStorage;
89  import com.liferay.portal.webdav.WebDAVUtil;
90  import com.liferay.portlet.PortletConfigFactory;
91  import com.liferay.portlet.PortletFilterFactory;
92  import com.liferay.portlet.PortletInstanceFactoryUtil;
93  import com.liferay.portlet.PortletURLListenerFactory;
94  import com.liferay.portlet.social.model.SocialActivityInterpreter;
95  import com.liferay.portlet.social.model.SocialRequestInterpreter;
96  import com.liferay.portlet.social.model.impl.SocialActivityInterpreterImpl;
97  import com.liferay.portlet.social.model.impl.SocialRequestInterpreterImpl;
98  import com.liferay.portlet.social.service.SocialActivityInterpreterLocalServiceUtil;
99  import com.liferay.portlet.social.service.SocialRequestInterpreterLocalServiceUtil;
100 import com.liferay.util.servlet.DynamicServletRequest;
101 import com.liferay.util.servlet.EncryptedServletRequest;
102 
103 import java.io.IOException;
104 
105 import java.util.Iterator;
106 import java.util.List;
107 import java.util.Set;
108 
109 import javax.portlet.PortletConfig;
110 import javax.portlet.PortletContext;
111 import javax.portlet.PortletException;
112 
113 import javax.servlet.RequestDispatcher;
114 import javax.servlet.ServletContext;
115 import javax.servlet.ServletException;
116 import javax.servlet.http.HttpServletRequest;
117 import javax.servlet.http.HttpServletResponse;
118 import javax.servlet.http.HttpSession;
119 import javax.servlet.jsp.PageContext;
120 
121 import org.apache.struts.Globals;
122 import org.apache.struts.action.ActionServlet;
123 import org.apache.struts.action.RequestProcessor;
124 import org.apache.struts.config.ControllerConfig;
125 import org.apache.struts.config.ModuleConfig;
126 import org.apache.struts.tiles.TilesUtilImpl;
127 
128 /**
129  * <a href="MainServlet.java.html"><b><i>View Source</i></b></a>
130  *
131  * @author Brian Wing Shun Chan
132  * @author Jorge Ferrer
133  * @author Brian Myunghun Kim
134  */
135 public class MainServlet extends ActionServlet {
136 
137     public void destroy() {
138         List<Portlet> portlets = PortletLocalServiceUtil.getPortlets();
139 
140         if (_log.isDebugEnabled()) {
141             _log.debug("Destroy schedulers");
142         }
143 
144         try {
145             destroySchedulers(portlets);
146         }
147         catch (Exception e) {
148             _log.error(e, e);
149         }
150 
151         if (_log.isDebugEnabled()) {
152             _log.debug("Destroy portlets");
153         }
154 
155         try {
156             destroyPortlets(portlets);
157         }
158         catch (Exception e) {
159             _log.error(e, e);
160         }
161 
162         if (_log.isDebugEnabled()) {
163             _log.debug("Destroy companies");
164         }
165 
166         try {
167             destroyCompanies();
168         }
169         catch (Exception e) {
170             _log.error(e, e);
171         }
172 
173         if (_log.isDebugEnabled()) {
174             _log.debug("Process global shutdown events");
175         }
176 
177         try {
178             processGlobalShutdownEvents();
179         }
180         catch (Exception e) {
181             _log.error(e, e);
182         }
183 
184         if (_log.isDebugEnabled()) {
185             _log.debug("Destroy");
186         }
187 
188         callParentDestroy();
189     }
190 
191     public void init() throws ServletException {
192         if (_log.isDebugEnabled()) {
193             _log.debug("Initialize");
194         }
195 
196         callParentInit();
197 
198         if (_log.isDebugEnabled()) {
199             _log.debug("Process startup events");
200         }
201 
202         try {
203             processStartupEvents();
204         }
205         catch (Exception e) {
206             _log.error(e, e);
207 
208             System.out.println(
209                 "Stopping the server due to unexpected startup errors");
210 
211             System.exit(0);
212         }
213 
214         if (_log.isDebugEnabled()) {
215             _log.debug("Initialize velocity");
216         }
217 
218         try {
219             initVelocity();
220         }
221         catch (Exception e) {
222             _log.error(e, e);
223         }
224 
225         if (_log.isDebugEnabled()) {
226             _log.debug("Initialize plugin package");
227         }
228 
229         PluginPackage pluginPackage = null;
230 
231         try {
232             pluginPackage = initPluginPackage();
233         }
234         catch (Exception e) {
235             _log.error(e, e);
236         }
237 
238         if (_log.isDebugEnabled()) {
239             _log.debug("Initialize portlets");
240         }
241 
242         List<Portlet> portlets = null;
243 
244         try {
245             portlets = initPortlets(pluginPackage);
246         }
247         catch (Exception e) {
248             _log.error(e, e);
249         }
250 
251         if (_log.isDebugEnabled()) {
252             _log.debug("Initialize layout templates");
253         }
254 
255         try {
256             initLayoutTemplates(pluginPackage, portlets);
257         }
258         catch (Exception e) {
259             _log.error(e, e);
260         }
261 
262         if (_log.isDebugEnabled()) {
263             _log.debug("Initialize themes");
264         }
265 
266         try {
267             initThemes(pluginPackage, portlets);
268         }
269         catch (Exception e) {
270             _log.error(e, e);
271         }
272 
273         if (_log.isDebugEnabled()) {
274             _log.debug("Initialize indexers");
275         }
276 
277         try {
278             initIndexers(portlets);
279         }
280         catch (Exception e) {
281             _log.error(e, e);
282         }
283 
284         if (_log.isDebugEnabled()) {
285             _log.debug("Initialize schedulers");
286         }
287 
288         try {
289             initSchedulers(portlets);
290         }
291         catch (Exception e) {
292             _log.error(e, e);
293         }
294 
295         if (_log.isDebugEnabled()) {
296             _log.debug("Initialize poller processors");
297         }
298 
299         try {
300             initPollerProcessors(portlets);
301         }
302         catch (Exception e) {
303             _log.error(e, e);
304         }
305 
306         if (_log.isDebugEnabled()) {
307             _log.debug("Initialize POP message listeners");
308         }
309 
310         try {
311             initPOPMessageListeners(portlets);
312         }
313         catch (Exception e) {
314             _log.error(e, e);
315         }
316 
317         if (_log.isDebugEnabled()) {
318             _log.debug("Initialize social activity interpreters");
319         }
320 
321         try {
322             initSocialActivityInterpreters(portlets);
323         }
324         catch (Exception e) {
325             _log.error(e, e);
326         }
327 
328         if (_log.isDebugEnabled()) {
329             _log.debug("Initialize social request interpreters");
330         }
331 
332         try {
333             initSocialRequestInterpreters(portlets);
334         }
335         catch (Exception e) {
336             _log.error(e, e);
337         }
338 
339         if (_log.isDebugEnabled()) {
340             _log.debug("Initialize WebDAV storages");
341         }
342 
343         try {
344             initWebDAVStorages(portlets);
345         }
346         catch (Exception e) {
347             _log.error(e, e);
348         }
349 
350         if (_log.isDebugEnabled()) {
351             _log.debug("Initialize web settings");
352         }
353 
354         try {
355             initWebSettings();
356         }
357         catch (Exception e) {
358             _log.error(e, e);
359         }
360 
361         if (_log.isDebugEnabled()) {
362             _log.debug("Initialize extension environment");
363         }
364 
365         try {
366             initExt();
367         }
368         catch (Exception e) {
369             _log.error(e, e);
370         }
371 
372         if (_log.isDebugEnabled()) {
373             _log.debug("Process global startup events");
374         }
375 
376         try {
377             processGlobalStartupEvents();
378         }
379         catch (Exception e) {
380             _log.error(e, e);
381         }
382 
383         if (_log.isDebugEnabled()) {
384             _log.debug("Initialize resource actions");
385         }
386 
387         try {
388             initResourceActions(portlets);
389         }
390         catch (Exception e) {
391             _log.error(e, e);
392         }
393 
394         if (_log.isDebugEnabled()) {
395             _log.debug("Initialize resource codes");
396         }
397 
398         try {
399             initResourceCodes(portlets);
400         }
401         catch (Exception e) {
402             _log.error(e, e);
403         }
404 
405         if (_log.isDebugEnabled()) {
406             _log.debug("Initialize companies");
407         }
408 
409         try {
410             initCompanies();
411         }
412         catch (Exception e) {
413             _log.error(e, e);
414         }
415 
416         if (_log.isDebugEnabled()) {
417             _log.debug("Initialize message resources");
418         }
419 
420         try {
421             initMessageResources();
422         }
423         catch (Exception e) {
424             _log.error(e, e);
425         }
426 
427         if (_log.isDebugEnabled()) {
428             _log.debug("Initialize plugins");
429         }
430 
431         try {
432             initPlugins();
433         }
434         catch (Exception e) {
435             _log.error(e, e);
436         }
437     }
438 
439     public void service(
440             HttpServletRequest request, HttpServletResponse response)
441         throws IOException, ServletException {
442 
443         if (_log.isDebugEnabled()) {
444             _log.debug("Process service request");
445         }
446 
447         if (processShutdownRequest(request, response)) {
448             if (_log.isDebugEnabled()) {
449                 _log.debug("Processed shutdown request");
450             }
451 
452             return;
453         }
454 
455         if (processMaintenanceRequest(request, response)) {
456             if (_log.isDebugEnabled()) {
457                 _log.debug("Processed maintenance request");
458             }
459 
460             return;
461         }
462 
463         if (_log.isDebugEnabled()) {
464             _log.debug("Get company id");
465         }
466 
467         long companyId = getCompanyId(request);
468 
469         if (_log.isDebugEnabled()) {
470             _log.debug("Set portal port");
471         }
472 
473         setPortalPort(request);
474 
475         if (_log.isDebugEnabled()) {
476             _log.debug("Check variables");
477         }
478 
479         checkServletContext(request);
480         checkPortletSessionTracker(request);
481         checkPortletRequestProcessor(request);
482         checkTilesDefinitionsFactory();
483 
484         if (_log.isDebugEnabled()) {
485             _log.debug("Encrypt request");
486         }
487 
488         request = encryptRequest(request, companyId);
489 
490         long userId = getUserId(request);
491         String remoteUser = getRemoteUser(request, userId);
492 
493         if (_log.isDebugEnabled()) {
494             _log.debug("Protect request");
495         }
496 
497         request = protectRequest(request, remoteUser);
498 
499         if (_log.isDebugEnabled()) {
500             _log.debug("Set principal");
501         }
502 
503         setPrincipalName(userId, remoteUser);
504 
505         try {
506             if (_log.isDebugEnabled()) {
507                 _log.debug(
508                 "Authenticate user id " + userId + " and remote user " +
509                     remoteUser);
510             }
511 
512             userId = loginUser(request, response, userId, remoteUser);
513 
514             if (_log.isDebugEnabled()) {
515                 _log.debug("Authenticated user id " + userId);
516             }
517         }
518         catch (Exception e) {
519             _log.error(e, e);
520         }
521 
522         if (_log.isDebugEnabled()) {
523             _log.debug("Process service pre events");
524         }
525 
526         if (processServicePre(request, response, userId)) {
527             if (_log.isDebugEnabled()) {
528                 _log.debug("Processing service pre events has errors");
529             }
530 
531             return;
532         }
533 
534         if (hasAbsoluteRedirect(request)) {
535             if (_log.isDebugEnabled()) {
536                 String currentURL = PortalUtil.getCurrentURL(request);
537 
538                 _log.debug(
539                     "Current URL " + currentURL + " has absolute redirect");
540             }
541 
542             return;
543         }
544 
545         if (!hasThemeDisplay(request)) {
546             if (_log.isDebugEnabled()) {
547                 String currentURL = PortalUtil.getCurrentURL(request);
548 
549                 _log.debug(
550                     "Current URL " + currentURL +
551                         " does not have a theme display");
552             }
553 
554             return;
555         }
556 
557         try {
558             if (_log.isDebugEnabled()) {
559                 _log.debug("Call parent service");
560             }
561 
562             callParentService(request, response);
563         }
564         finally {
565             if (_log.isDebugEnabled()) {
566                 _log.debug("Process service post events");
567             }
568 
569             processServicePost(request, response);
570         }
571     }
572 
573     protected void callParentDestroy() {
574         super.destroy();
575     }
576 
577     protected void callParentInit() throws ServletException {
578         super.init();
579     }
580 
581     protected void callParentService(
582             HttpServletRequest request, HttpServletResponse response)
583         throws IOException, ServletException {
584 
585         super.service(request, response);
586     }
587 
588     protected void checkPortletRequestProcessor(HttpServletRequest request)
589         throws ServletException {
590 
591         ServletContext servletContext = getServletContext();
592 
593         PortletRequestProcessor portletReqProcessor =
594             (PortletRequestProcessor)servletContext.getAttribute(
595                 WebKeys.PORTLET_STRUTS_PROCESSOR);
596 
597         if (portletReqProcessor == null) {
598             ModuleConfig moduleConfig = getModuleConfig(request);
599 
600             portletReqProcessor =
601                 PortletRequestProcessor.getInstance(this, moduleConfig);
602 
603             servletContext.setAttribute(
604                 WebKeys.PORTLET_STRUTS_PROCESSOR, portletReqProcessor);
605         }
606     }
607 
608     protected void checkPortletSessionTracker(HttpServletRequest request) {
609         HttpSession session = request.getSession();
610 
611         if (session.getAttribute(WebKeys.PORTLET_SESSION_TRACKER) != null) {
612             return;
613         }
614 
615         session.setAttribute(
616             WebKeys.PORTLET_SESSION_TRACKER,
617             PortletSessionTracker.getInstance());
618     }
619 
620     protected void checkServletContext(HttpServletRequest request) {
621         ServletContext servletContext = getServletContext();
622 
623         request.setAttribute(WebKeys.CTX, servletContext);
624     }
625 
626     protected void checkTilesDefinitionsFactory() {
627         ServletContext servletContext = getServletContext();
628 
629         if (servletContext.getAttribute(
630                 TilesUtilImpl.DEFINITIONS_FACTORY) != null) {
631 
632             return;
633         }
634 
635         servletContext.setAttribute(
636             TilesUtilImpl.DEFINITIONS_FACTORY,
637             servletContext.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY));
638     }
639 
640     protected void checkWebSettings(String xml) throws DocumentException {
641         Document doc = SAXReaderUtil.read(xml);
642 
643         Element root = doc.getRootElement();
644 
645         int timeout = PropsValues.SESSION_TIMEOUT;
646 
647         Element sessionConfig = root.element("session-config");
648 
649         if (sessionConfig != null) {
650             String sessionTimeout = sessionConfig.elementText(
651                 "session-timeout");
652 
653             timeout = GetterUtil.getInteger(sessionTimeout, timeout);
654         }
655 
656         PropsUtil.set(PropsKeys.SESSION_TIMEOUT, String.valueOf(timeout));
657 
658         PropsValues.SESSION_TIMEOUT = timeout;
659 
660         I18nServlet.setLanguageIds(root);
661         I18nFilter.setLanguageIds(I18nServlet.getLanguageIds());
662     }
663 
664     protected void destroyCompanies() throws Exception {
665         long[] companyIds = PortalInstances.getCompanyIds();
666 
667         for (int i = 0; i < companyIds.length; i++) {
668             destroyCompany(companyIds[i]);
669         }
670     }
671 
672     protected void destroyCompany(long companyId) {
673         if (_log.isDebugEnabled()) {
674             _log.debug("Process shutdown events");
675         }
676 
677         try {
678             EventsProcessorUtil.process(
679                 PropsKeys.APPLICATION_SHUTDOWN_EVENTS,
680                 PropsValues.APPLICATION_SHUTDOWN_EVENTS,
681                 new String[] {String.valueOf(companyId)});
682         }
683         catch (Exception e) {
684             _log.error(e, e);
685         }
686     }
687 
688     protected void destroyPortlets(List<Portlet> portlets) throws Exception {
689         Iterator<Portlet> itr = portlets.iterator();
690 
691         while (itr.hasNext()) {
692             Portlet portlet = itr.next();
693 
694             PortletInstanceFactoryUtil.destroy(portlet);
695         }
696     }
697 
698     protected void destroySchedulers(List<Portlet> portlets) throws Exception {
699         if (!PropsValues.SCHEDULER_ENABLED) {
700             return;
701         }
702 
703         for (String className : PropsValues.SCHEDULER_CLASSES) {
704             Scheduler scheduler = (Scheduler)InstancePool.get(className, false);
705 
706             if (scheduler != null) {
707                 scheduler.unschedule();
708             }
709         }
710 
711         Iterator<Portlet> itr = portlets.iterator();
712 
713         while (itr.hasNext()) {
714             Portlet portlet = itr.next();
715 
716             String className = portlet.getSchedulerClass();
717 
718             if (!portlet.isActive() || Validator.isNull(className)) {
719                 continue;
720             }
721 
722             Scheduler scheduler = (Scheduler)InstancePool.get(className, false);
723 
724             if (scheduler != null) {
725                 scheduler.unschedule();
726             }
727         }
728     }
729 
730     protected HttpServletRequest encryptRequest(
731         HttpServletRequest request, long companyId) {
732 
733         boolean encryptRequest = ParamUtil.getBoolean(request, WebKeys.ENCRYPT);
734 
735         if (!encryptRequest) {
736             return request;
737         }
738 
739         try {
740             Company company = CompanyLocalServiceUtil.getCompanyById(
741                 companyId);
742 
743             request = new EncryptedServletRequest(
744                 request, company.getKeyObj());
745         }
746         catch (Exception e) {
747         }
748 
749         return request;
750     }
751 
752     protected long getCompanyId(HttpServletRequest request) {
753         return PortalInstances.getCompanyId(request);
754     }
755 
756     protected String getRemoteUser(
757         HttpServletRequest request, long userId) {
758 
759         String remoteUser = request.getRemoteUser();
760 
761         if (!PropsValues.PORTAL_JAAS_ENABLE) {
762             HttpSession session = request.getSession();
763 
764             String jRemoteUser = (String)session.getAttribute("j_remoteuser");
765 
766             if (jRemoteUser != null) {
767                 remoteUser = jRemoteUser;
768 
769                 session.removeAttribute("j_remoteuser");
770             }
771         }
772 
773         if ((userId > 0) && (remoteUser == null)) {
774             remoteUser = String.valueOf(userId);
775         }
776 
777         return remoteUser;
778     }
779 
780     protected synchronized RequestProcessor getRequestProcessor(
781             ModuleConfig moduleConfig)
782         throws ServletException {
783 
784         ServletContext servletContext = getServletContext();
785 
786         String key = Globals.REQUEST_PROCESSOR_KEY + moduleConfig.getPrefix();
787 
788         RequestProcessor processor =
789             (RequestProcessor)servletContext.getAttribute(key);
790 
791         if (processor == null) {
792             ControllerConfig controllerConfig =
793                 moduleConfig.getControllerConfig();
794 
795             String processorClass = controllerConfig.getProcessorClass();
796 
797             ClassLoader classLoader = PortalClassLoaderUtil.getClassLoader();
798 
799             try {
800                 processor = (RequestProcessor)classLoader.loadClass(
801                     processorClass).newInstance();
802             }
803             catch (Exception e) {
804                 throw new ServletException(e);
805             }
806 
807             processor.init(this, moduleConfig);
808 
809             servletContext.setAttribute(key, processor);
810         }
811 
812         return processor;
813     }
814 
815     protected long getUserId(HttpServletRequest request) {
816         return PortalUtil.getUserId(request);
817     }
818 
819     protected boolean hasAbsoluteRedirect(HttpServletRequest request) {
820         if (request.getAttribute(
821                 AbsoluteRedirectsResponse.class.getName()) == null) {
822 
823             return false;
824         }
825         else {
826             return true;
827         }
828     }
829 
830     protected boolean hasThemeDisplay(HttpServletRequest request) {
831         if (request.getAttribute(WebKeys.THEME_DISPLAY) == null) {
832             return false;
833         }
834         else {
835             return true;
836         }
837     }
838 
839     protected void initCompanies() throws Exception {
840         ServletContext servletContext = getServletContext();
841 
842         String[] webIds = PortalInstances.getWebIds();
843 
844         for (int i = 0; i < webIds.length; i++) {
845             PortalInstances.initCompany(servletContext, webIds[i]);
846         }
847     }
848 
849     protected void initExt() throws Exception {
850         ServletContext servletContext = getServletContext();
851 
852         ExtRegistry.registerPortal(servletContext);
853     }
854 
855     protected void initIndexers(List<Portlet> portlets) throws Exception {
856         Iterator<Portlet> itr = portlets.iterator();
857 
858         while (itr.hasNext()) {
859             Portlet portlet = itr.next();
860 
861             String indexerClass = portlet.getIndexerClass();
862 
863             if (!portlet.isActive() || Validator.isNull(indexerClass)) {
864                 continue;
865             }
866 
867             Indexer indexer = (Indexer)InstancePool.get(indexerClass);
868 
869             IndexerRegistryUtil.register(indexer);
870         }
871     }
872 
873     protected void initLayoutTemplates(
874             PluginPackage pluginPackage, List<Portlet> portlets)
875         throws Exception {
876 
877         ServletContext servletContext = getServletContext();
878 
879         String[] xmls = new String[] {
880             HttpUtil.URLtoString(
881                 servletContext.getResource(
882                     "/WEB-INF/liferay-layout-templates.xml")),
883             HttpUtil.URLtoString(
884                 servletContext.getResource(
885                     "/WEB-INF/liferay-layout-templates-ext.xml"))
886         };
887 
888         LayoutTemplateLocalServiceUtil.init(
889             servletContext, xmls, pluginPackage);
890     }
891 
892     protected void initMessageResources() throws Exception {
893         ServletContext servletContext = getServletContext();
894 
895         MultiMessageResources messageResources =
896             (MultiMessageResources)servletContext.getAttribute(
897                 Globals.MESSAGES_KEY);
898 
899         LanguageResources.init(messageResources);
900     }
901 
902     protected PluginPackage initPluginPackage() throws Exception {
903         ServletContext servletContext = getServletContext();
904 
905         return PluginPackageHotDeployListener.readPluginPackage(servletContext);
906     }
907 
908     protected void initPlugins() throws Exception {
909 
910         // See LEP-2885. Don't flush hot deploy events until after the portal
911         // has initialized.
912 
913         PortalInitableUtil.flushInitables();
914         HotDeployUtil.flushPrematureEvents();
915     }
916 
917     protected void initPollerProcessors(List<Portlet> portlets)
918         throws Exception {
919 
920         Iterator<Portlet> itr = portlets.iterator();
921 
922         while (itr.hasNext()) {
923             Portlet portlet = itr.next();
924 
925             PollerProcessor pollerProcessor =
926                 portlet.getPollerProcessorInstance();
927 
928             if (!portlet.isActive() || (pollerProcessor == null)) {
929                 continue;
930             }
931 
932             PollerProcessorUtil.addPollerProcessor(
933                 portlet.getPortletId(), pollerProcessor);
934         }
935     }
936 
937     protected void initPOPMessageListeners(List<Portlet> portlets)
938         throws Exception {
939 
940         Iterator<Portlet> itr = portlets.iterator();
941 
942         while (itr.hasNext()) {
943             Portlet portlet = itr.next();
944 
945             MessageListener popMessageListener =
946                 portlet.getPopMessageListenerInstance();
947 
948             if (!portlet.isActive() || (popMessageListener == null)) {
949                 continue;
950             }
951 
952             POPServerUtil.addListener(popMessageListener);
953         }
954     }
955 
956     protected void initPortletApp(
957             Portlet portlet, ServletContext servletContext)
958         throws PortletException {
959 
960         PortletApp portletApp = portlet.getPortletApp();
961 
962         PortletConfig portletConfig = PortletConfigFactory.create(
963             portlet, servletContext);
964 
965         PortletContext portletContext = portletConfig.getPortletContext();
966 
967         Set<PortletFilter> portletFilters = portletApp.getPortletFilters();
968 
969         for (PortletFilter portletFilter : portletFilters) {
970             PortletFilterFactory.create(portletFilter, portletContext);
971         }
972 
973         Set<PortletURLListener> portletURLListeners =
974             portletApp.getPortletURLListeners();
975 
976         for (PortletURLListener portletURLListener : portletURLListeners) {
977             PortletURLListenerFactory.create(portletURLListener);
978         }
979     }
980 
981     protected List<Portlet> initPortlets(PluginPackage pluginPackage)
982         throws Exception {
983 
984         ServletContext servletContext = getServletContext();
985 
986         String[] xmls = new String[] {
987             HttpUtil.URLtoString(
988                 servletContext.getResource(
989                     "/WEB-INF/" + Portal.PORTLET_XML_FILE_NAME_CUSTOM)),
990             HttpUtil.URLtoString(
991                 servletContext.getResource("/WEB-INF/portlet-ext.xml")),
992             HttpUtil.URLtoString(
993                 servletContext.getResource("/WEB-INF/liferay-portlet.xml")),
994             HttpUtil.URLtoString(
995                 servletContext.getResource("/WEB-INF/liferay-portlet-ext.xml")),
996             HttpUtil.URLtoString(
997                 servletContext.getResource("/WEB-INF/web.xml"))
998         };
999 
1000        PortletLocalServiceUtil.initEAR(servletContext, xmls, pluginPackage);
1001
1002        List<Portlet> portlets = PortletLocalServiceUtil.getPortlets();
1003
1004        for (int i = 0; i < portlets.size(); i++) {
1005            Portlet portlet = portlets.get(i);
1006
1007            if (i == 0) {
1008                initPortletApp(portlet, servletContext);
1009            }
1010
1011            PortletInstanceFactoryUtil.create(portlet, servletContext);
1012        }
1013
1014        return portlets;
1015    }
1016
1017    protected void initResourceActions(List<Portlet> portlets)
1018        throws Exception {
1019
1020        Iterator<Portlet> itr = portlets.iterator();
1021
1022        while (itr.hasNext()) {
1023            Portlet portlet = itr.next();
1024
1025            List<String> portletActions =
1026                ResourceActionsUtil.getPortletResourceActions(
1027                    portlet.getPortletId());
1028
1029            ResourceActionLocalServiceUtil.checkResourceActions(
1030                portlet.getPortletId(), portletActions);
1031
1032            List<String> modelNames =
1033                ResourceActionsUtil.getPortletModelResources(
1034                    portlet.getPortletId());
1035
1036            for (String modelName : modelNames) {
1037                List<String> modelActions =
1038                    ResourceActionsUtil.getModelResourceActions(modelName);
1039
1040                ResourceActionLocalServiceUtil.checkResourceActions(
1041                    modelName, modelActions);
1042            }
1043        }
1044    }
1045
1046    protected void initResourceCodes(List<Portlet> portlets) throws Exception {
1047        long[] companyIds = PortalInstances.getCompanyIdsBySQL();
1048
1049        Iterator<Portlet> itr = portlets.iterator();
1050
1051        while (itr.hasNext()) {
1052            Portlet portlet = itr.next();
1053
1054            List<String> modelNames =
1055                ResourceActionsUtil.getPortletModelResources(
1056                    portlet.getPortletId());
1057
1058            for (long companyId : companyIds) {
1059                ResourceCodeLocalServiceUtil.checkResourceCodes(
1060                    companyId, portlet.getPortletId());
1061
1062                for (String modelName : modelNames) {
1063                    ResourceCodeLocalServiceUtil.checkResourceCodes(
1064                        companyId, modelName);
1065                }
1066            }
1067        }
1068    }
1069
1070    protected void initSchedulers(List<Portlet> portlets) throws Exception {
1071        if (!PropsValues.SCHEDULER_ENABLED) {
1072            return;
1073        }
1074
1075        for (String className : PropsValues.SCHEDULER_CLASSES) {
1076            Scheduler scheduler = (Scheduler)InstancePool.get(className);
1077
1078            scheduler.schedule();
1079        }
1080
1081        Iterator<Portlet> itr = portlets.iterator();
1082
1083        while (itr.hasNext()) {
1084            Portlet portlet = itr.next();
1085
1086            String className = portlet.getSchedulerClass();
1087
1088            if (!portlet.isActive() || Validator.isNull(className)) {
1089                continue;
1090            }
1091
1092            Scheduler scheduler = (Scheduler)InstancePool.get(className);
1093
1094            scheduler.schedule();
1095        }
1096    }
1097
1098    protected void initSocialActivityInterpreters(List<Portlet> portlets)
1099        throws Exception {
1100
1101        Iterator<Portlet> itr = portlets.iterator();
1102
1103        while (itr.hasNext()) {
1104            Portlet portlet = itr.next();
1105
1106            SocialActivityInterpreter socialActivityInterpreter =
1107                portlet.getSocialActivityInterpreterInstance();
1108
1109            if (!portlet.isActive() ||
1110                (socialActivityInterpreter == null)) {
1111
1112                continue;
1113            }
1114
1115            socialActivityInterpreter = new SocialActivityInterpreterImpl(
1116                portlet.getPortletId(), socialActivityInterpreter);
1117
1118            SocialActivityInterpreterLocalServiceUtil.addActivityInterpreter(
1119                socialActivityInterpreter);
1120        }
1121    }
1122
1123    protected void initSocialRequestInterpreters(List<Portlet> portlets)
1124        throws Exception {
1125
1126        Iterator<Portlet> itr = portlets.iterator();
1127
1128        while (itr.hasNext()) {
1129            Portlet portlet = itr.next();
1130
1131            SocialRequestInterpreter socialRequestInterpreter =
1132                portlet.getSocialRequestInterpreterInstance();
1133
1134            if (!portlet.isActive() || (socialRequestInterpreter == null)) {
1135                continue;
1136            }
1137
1138            socialRequestInterpreter = new SocialRequestInterpreterImpl(
1139                portlet.getPortletId(), socialRequestInterpreter);
1140
1141            SocialRequestInterpreterLocalServiceUtil.addRequestInterpreter(
1142                socialRequestInterpreter);
1143        }
1144    }
1145
1146    protected void initThemes(
1147            PluginPackage pluginPackage, List<Portlet> portlets)
1148        throws Exception {
1149
1150        ServletContext servletContext = getServletContext();
1151
1152        String[] xmls = new String[] {
1153            HttpUtil.URLtoString(
1154                servletContext.getResource(
1155                    "/WEB-INF/liferay-look-and-feel.xml")),
1156            HttpUtil.URLtoString(
1157                servletContext.getResource(
1158                    "/WEB-INF/liferay-look-and-feel-ext.xml"))
1159        };
1160
1161        ThemeLocalServiceUtil.init(
1162            servletContext, null, true, xmls, pluginPackage);
1163    }
1164
1165    protected void initVelocity() throws Exception {
1166        ServletContext servletContext = getServletContext();
1167
1168        String contextPath = PortalUtil.getPathContext();
1169
1170        VelocityContextPool.put(contextPath, servletContext);
1171    }
1172
1173    protected void initWebDAVStorages(List<Portlet> portlets) throws Exception {
1174        Iterator<Portlet> itr = portlets.iterator();
1175
1176        while (itr.hasNext()) {
1177            Portlet portlet = itr.next();
1178
1179            WebDAVStorage webDAVStorage = portlet.getWebDAVStorageInstance();
1180
1181            if (!portlet.isActive() || (webDAVStorage == null)) {
1182                continue;
1183            }
1184
1185            webDAVStorage.setToken(portlet.getWebDAVStorageToken());
1186
1187            WebDAVUtil.addStorage(webDAVStorage);
1188        }
1189    }
1190
1191    protected void initWebSettings() throws Exception {
1192        ServletContext servletContext = getServletContext();
1193
1194        String xml = HttpUtil.URLtoString(
1195            servletContext.getResource("/WEB-INF/web.xml"));
1196
1197        checkWebSettings(xml);
1198    }
1199
1200    protected long loginUser(
1201            HttpServletRequest request, HttpServletResponse response,
1202            long userId, String remoteUser)
1203        throws PortalException, SystemException {
1204
1205        if ((userId > 0) || (remoteUser == null)) {
1206            return userId;
1207        }
1208
1209        userId = GetterUtil.getLong(remoteUser);
1210
1211        EventsProcessorUtil.process(
1212            PropsKeys.LOGIN_EVENTS_PRE, PropsValues.LOGIN_EVENTS_PRE, request,
1213            response);
1214
1215        User user = UserLocalServiceUtil.getUserById(userId);
1216
1217        if (PropsValues.USERS_UPDATE_LAST_LOGIN) {
1218            UserLocalServiceUtil.updateLastLogin(
1219                userId, request.getRemoteAddr());
1220        }
1221
1222        HttpSession session = request.getSession();
1223
1224        session.setAttribute(WebKeys.USER_ID, new Long(userId));
1225        session.setAttribute(Globals.LOCALE_KEY, user.getLocale());
1226
1227        EventsProcessorUtil.process(
1228            PropsKeys.LOGIN_EVENTS_POST, PropsValues.LOGIN_EVENTS_POST,
1229            request, response);
1230
1231        return userId;
1232    }
1233
1234    protected void processGlobalShutdownEvents() throws Exception {
1235        EventsProcessorUtil.process(
1236            PropsKeys.GLOBAL_SHUTDOWN_EVENTS,
1237            PropsValues.GLOBAL_SHUTDOWN_EVENTS);
1238
1239        super.destroy();
1240    }
1241
1242    protected void processGlobalStartupEvents() throws Exception {
1243        EventsProcessorUtil.process(
1244            PropsKeys.GLOBAL_STARTUP_EVENTS, PropsValues.GLOBAL_STARTUP_EVENTS);
1245    }
1246
1247    protected boolean processMaintenanceRequest(
1248            HttpServletRequest request, HttpServletResponse response)
1249        throws IOException, ServletException {
1250
1251        if (!MaintenanceUtil.isMaintaining()) {
1252            return false;
1253        }
1254
1255        RequestDispatcher requestDispatcher = request.getRequestDispatcher(
1256            "/html/portal/maintenance.jsp");
1257
1258        requestDispatcher.include(request, response);
1259
1260        return true;
1261    }
1262
1263    protected void processServicePost(
1264        HttpServletRequest request, HttpServletResponse response) {
1265
1266        try {
1267            EventsProcessorUtil.process(
1268                PropsKeys.SERVLET_SERVICE_EVENTS_POST,
1269                PropsValues.SERVLET_SERVICE_EVENTS_POST, request, response);
1270        }
1271        catch (Exception e) {
1272            _log.error(e, e);
1273        }
1274
1275        response.addHeader(
1276            _LIFERAY_PORTAL_REQUEST_HEADER, ReleaseInfo.getReleaseInfo());
1277    }
1278
1279    protected boolean processServicePre(
1280            HttpServletRequest request, HttpServletResponse response,
1281            long userId)
1282        throws IOException, ServletException {
1283
1284        try {
1285            EventsProcessorUtil.process(
1286                PropsKeys.SERVLET_SERVICE_EVENTS_PRE,
1287                PropsValues.SERVLET_SERVICE_EVENTS_PRE, request, response);
1288        }
1289        catch (Exception e) {
1290            Throwable cause = e.getCause();
1291
1292            if (cause instanceof NoSuchLayoutException) {
1293                sendError(
1294                    HttpServletResponse.SC_NOT_FOUND, cause, request, response);
1295
1296                return true;
1297            }
1298            else if (cause instanceof PrincipalException) {
1299                processServicePrePrincipalException(
1300                    cause, userId, request, response);
1301
1302                return true;
1303            }
1304
1305            _log.error(e, e);
1306
1307            request.setAttribute(PageContext.EXCEPTION, e);
1308
1309            ServletContext servletContext = getServletContext();
1310
1311            StrutsUtil.forward(
1312                PropsValues.SERVLET_SERVICE_EVENTS_PRE_ERROR_PAGE,
1313                servletContext, request, response);
1314
1315            return true;
1316        }
1317
1318        return false;
1319    }
1320
1321    protected void processServicePrePrincipalException(
1322            Throwable t, long userId, HttpServletRequest request,
1323            HttpServletResponse response)
1324        throws IOException, ServletException {
1325
1326        if (userId > 0) {
1327            sendError(
1328                HttpServletResponse.SC_UNAUTHORIZED, t, request, response);
1329
1330            return;
1331        }
1332
1333        String redirect =
1334            request.getContextPath() + Portal.PATH_MAIN + "/portal/login";
1335
1336        String currentURL = PortalUtil.getCurrentURL(request);
1337
1338        redirect = HttpUtil.addParameter(redirect, "redirect", currentURL);
1339
1340        long plid = ParamUtil.getLong(request, "p_l_id");
1341
1342        if (plid > 0) {
1343            try {
1344                Layout layout = LayoutLocalServiceUtil.getLayout(plid);
1345
1346                if (layout.getGroup().isStagingGroup()) {
1347                    Group group = GroupLocalServiceUtil.getGroup(
1348                        layout.getCompanyId(), GroupConstants.GUEST);
1349
1350                    plid = group.getDefaultPublicPlid();
1351                }
1352                else if (layout.isPrivateLayout()) {
1353                    plid = LayoutLocalServiceUtil.getDefaultPlid(
1354                        layout.getGroupId(), false);
1355                }
1356
1357                redirect = HttpUtil.addParameter(redirect, "p_l_id", plid);
1358            }
1359            catch (Exception e) {
1360            }
1361        }
1362
1363        response.sendRedirect(redirect);
1364    }
1365
1366    protected boolean processShutdownRequest(
1367            HttpServletRequest request, HttpServletResponse response)
1368        throws IOException {
1369
1370        if (!ShutdownUtil.isShutdown()) {
1371            return false;
1372        }
1373
1374        response.setContentType(ContentTypes.TEXT_HTML_UTF8);
1375
1376        String html = ContentUtil.get(
1377            "com/liferay/portal/dependencies/shutdown.html");
1378
1379        response.getOutputStream().print(html);
1380
1381        return true;
1382    }
1383
1384    protected void processStartupEvents() throws Exception {
1385        StartupAction startupAction = new StartupAction();
1386
1387        startupAction.run(null);
1388    }
1389
1390    protected HttpServletRequest protectRequest(
1391        HttpServletRequest request, String remoteUser) {
1392
1393        // WebSphere will not return the remote user unless you are
1394        // authenticated AND accessing a protected path. Other servers will
1395        // return the remote user for all threads associated with an
1396        // authenticated user. We use ProtectedServletRequest to ensure we get
1397        // similar behavior across all servers.
1398
1399        return new ProtectedServletRequest(request, remoteUser);
1400    }
1401
1402    protected void sendError(
1403            int status, Throwable t, HttpServletRequest request,
1404            HttpServletResponse response)
1405        throws IOException, ServletException {
1406
1407        DynamicServletRequest dynamicRequest = new DynamicServletRequest(
1408            request);
1409
1410        // Reset p_l_id or there will be an infinite loop
1411
1412        dynamicRequest.setParameter("p_l_id", StringPool.BLANK);
1413
1414        PortalUtil.sendError(status, (Exception)t, dynamicRequest, response);
1415    }
1416
1417    protected void setPortalPort(HttpServletRequest request) {
1418        PortalUtil.setPortalPort(request);
1419    }
1420
1421    protected void setPrincipalName(long userId, String remoteUser) {
1422        if ((userId == 0) && (remoteUser == null)) {
1423            return;
1424        }
1425
1426        String name = String.valueOf(userId);
1427
1428        if (remoteUser != null) {
1429            name = remoteUser;
1430        }
1431
1432        PrincipalThreadLocal.setName(name);
1433    }
1434
1435    private static final String _LIFERAY_PORTAL_REQUEST_HEADER =
1436        "Liferay-Portal";
1437
1438    private static Log _log = LogFactoryUtil.getLog(MainServlet.class);
1439
1440}